Splitting up a string, c#

i have a string that gets generated and looks like this:

word1:word2:word3:word4

the words i want to find out a seperated by ":"

so i coded the following:

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

but when i try run it the right,complete words get read in, but i get an error (see above). i hope some of you can point what i am doing wrong


Use the Split method:

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

Now, you have all the words collected into an array which you can then enumerate upon or index into particular positions etc.

eg

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

Simply:

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

Then access the elements of words[]

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

上一篇: 存储库模式和导航属性

下一篇: 分割一个字符串,c#