Reputation: 297
I want to take a string from a textbox (txtFrom) and save the first word and save whatever is left in another part. (the whatever is left is everything past the first space)
Example string = "Bob jones went to the store"
array[0] would give "Bob"
array[1] would give "jones went to the store"
I know there is string[] array = txtFrom.Split(' ');
, but that gives me an array of 6 with individual words.
Upvotes: 19
Views: 50569
Reputation: 1057
and as method with long delimter:
public string[] SplitInTwoParts(string source, string delimiter){
string[] items = source.Split(new string[] { delimiter }, StringSplitOptions.None);
string firstItem = items[0];
string remainingItems = string.Join(delimiter, items.Skip(1).ToList());
return new string[] { firstItem, remainingItems };
}
Upvotes: 0
Reputation: 41236
You simply combine a split with a join to get the first element:
string[] items = source.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string firstItem = items[0];
string remainingItems = string.Join(" ", items.Skip(1).ToList());
You simply take the first item and then reform the remainder back into a string.
Upvotes: 4
Reputation: 21
char[] delimiterChars = { ' ', ',' };
string text = txtString.Text;
string[] words = text.Split(delimiterChars, 2);
txtString1.Text = words[0].ToString();
txtString2.Text = words[1].ToString();
Upvotes: 2
Reputation: 25495
You can also try RegularExpressions
Match M = System.Text.RegularExpressions.Regex.Match(source,"(.*?)\s(.*)");
M.Groups[1] //Bob
M.Groups[2] // jones went to the store
The regular expression matches everything up to the first space and stores it in the first group the ? mark tells it to make the smallest match possible. The second clause grabs everything after the space and stores it in the second group
Upvotes: 0
Reputation: 19601
There is an overload of the String.Split()
method which takes an integer representing the number of substrings to return.
So your method call would become: string[] array = txtFrom.Text.Split(' ', 2);
Upvotes: 3
Reputation: 301077
Use String.Split(Char[], Int32)
overload like this:
string[] array = txtFrom.Text.Split(new char[]{' '},2);
http://msdn.microsoft.com/en-us/library/c1bs0eda.aspx
Upvotes: 50