拆分字符串,c#

时间:2018-01-08 12:18:34

标签: 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; }
 }

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

3 个答案:

答案 0 :(得分:4)

使用Split方法:

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

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

e.g。

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

答案 1 :(得分:1)

请尝试以下代码。

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);
        }
    }
}

答案 2 :(得分:1)

简单地:

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

然后访问words[]

的元素