分割一个字符串,c#

我有一个生成的字符串,如下所示:

WORD1:WORD2:WORD3:word4

我想找到一个单独的词“:”

所以我编码如下:

string word1 = "";
string word2 = "";
string word3 = "";
string word4 = "";

int part = 1;
int last_sign = 0;

for (int i = 0; i < string1.Length; i++)
   {
       if (string1[i] == ':')
       {
          if (part == 2)
          {
           part = part + 1;
          }
       }
       if (part == 1)
       {
          word1 = word1 + string1[i];
       }
       if (part == 2)
       {
          word2 = word2 + string1[i];
       }
       if (part == 3)
       {
        word3 = word3 + string1[i];
       }
       if (part == 4)
       {
        word4 = word4 + string1[i];
       }
       if (last_sign == 0)
       {
        if (string1[i + 2] == (string1.Length - 3)) //this is the sign before the last sign 
                                                   //error line
        { last_sign = 1; }
       }
       if (last_sign == 1) //this is the last sign
        { break; }
 }

但是当我尝试运行它的权利,完整的单词读入,但我得到一个错误(见上文)。 我希望你们中的一些人能够指出我做错了什么


使用Split方法:

string[] words = string1.Split(':');

现在,您可以将所有单词收集到一个数组中,然后您可以枚举或将其索引到特定位置等。

例如

foreach (var word in words)
       Console.WriteLine(word);

尝试下面的代码。

class Program
{
    static void Main()
    {
        // Input string contain separators.
        string value1 = "word1:word2:word3:word4";
        char[] delimiter1 = new char[] { ':' };   // <-- Split on these

        // ... Use StringSplitOptions.None.
        string[] array1 = value1.Split(delimiter1,
            StringSplitOptions.None);

        foreach (string entry in array1)
        {
            Console.WriteLine(entry);
        }

        // ... Use StringSplitOptions.RemoveEmptyEntries.
        string[] array2 = value1.Split(delimiter1,
            StringSplitOptions.RemoveEmptyEntries);

        Console.WriteLine();
        foreach (string entry in array2)
        {
            Console.WriteLine(entry);
        }
    }
}

只是:

char[] delim = {':'};
string[] words = string1.Split(delim);

然后访问words[]的元素words[]

链接地址: http://www.djcxy.com/p/51393.html

上一篇: Splitting up a string, c#

下一篇: How to remove words in a flat file from a column string of words using SSIS