Sunday, April 24, 2005 5:48 PM triplez

C# Split By String

private string[] SplitByString(string testString, string split) { 
   int offset = 0;
   int index = 0;
   int[] offsets = new int[testString.Length + 1]; 

   while(index < testString.Length) { 
      int indexOf = testString.IndexOf(split, index); 
      if ( indexOf != -1 )  { 
         offsets[offset++] = indexOf; 
         index = (indexOf + split.Length); 
      } else { 
         index = testString.Length; 
      }
   }

   string[] final = new string[offset+1];
   if (offset == 0 ) { 
      final[0] = testString; 
   } else { 
      offset--; 
      final[0] = testString.Substring(0, offsets[0]); 
      for(int i = 0; i < offset; i++) { 
         final[i + 1] = testString.Substring(offsets[i] + split.Length, offsets[i+1] - offsets[i] - split.Length); 
      } 
      final[offset + 1] = testString.Substring(offsets[offset] + split.Length);
   } 
   return final;
}

This is a Split By String method. Hope you guys find it useful. 

Filed under:

# re: C# Split By String

Tuesday, April 26, 2005 9:11 PM by chuawenching

Nice snippets :)

# re: C# Split By String

Thursday, April 28, 2005 12:35 AM by triplez

Thanks.

# re: C# Split By String

Sunday, July 27, 2008 7:49 AM by NeXuS

Here is a nice short version for splitting strings with strings

string[] result = myString.Split(new string[] { "<>" }, StringSplitOptions.None);