[RESOLVED] spiliting string into two strings
Hi
I want to split a string into two strings
myString = "hello there are you there test yes I am here"
I need to split the string into two when it finds test
eg I want something like spilitString1 ="hello there are you there"
splitString2 = "yes I am here"
how do I do this spliting in c#?
Thanks
Re: spiliting string into two strings
Re: spiliting string into two strings
Here is an example where the splitter is a string in stead of a char array as in Hacks link:
Code:
String myString = "hello there are you there test yes I am here";
String splitter = " test ";
String splitString1 = myString.Substring(0, myString.IndexOf(splitter));
String splitString2 = myString.Substring(myString.IndexOf(splitter) + splitter.Length , myString.Length - (myString.IndexOf(splitter) + splitter.Length ));
Console.WriteLine("String 1: " + splitString1);
Console.WriteLine("String 2: " + splitString2);
- ØØ -
Re: spiliting string into two strings
just use Regex.Split :)
VB Code:
[COLOR=Blue]string[/COLOR] tmp = "this is a test string";
[COLOR=Blue]string[/COLOR][] buffer = System.Text.RegularExpressions.Regex.Split(tmp,"test");
Console.WriteLine(buffer[0]); [COLOR=Green]// this is the part before the word ' test ' [/COLOR]
Console.WriteLine("*** the word test was the split ***");
Console.WriteLine(buffer[1]); [COLOR=Green]// this is the part after the word ' test '[/COLOR]
Re: spiliting string into two strings
Just note that that overload of Regex.Split will split the string on every occurrence of the substring. That may be what you want, but you said you want to split the string in two, so it may be that you only want to split on the first occurrence. If you want to limit the number of substrings in the output you would have to use a different overload, and one that is not Shared I believe.
Re: spiliting string into two strings
Thank you all, especialy Noteme thanks for your code snippet. it works alright.
cheers