Splitting a String into only 2 parts

前端 未结 5 1106
抹茶落季
抹茶落季 2021-02-07 21:52

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)

相关标签:
5条回答
  • 2021-02-07 22:20

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

    0 讨论(0)
  • 2021-02-07 22:25

    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.

    0 讨论(0)
  • 2021-02-07 22:28

    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

    0 讨论(0)
  • 2021-02-07 22:35

    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

    0 讨论(0)
  • 2021-02-07 22:39
    char[] delimiterChars = { ' ', ',' };
    string text = txtString.Text;
    
    string[] words = text.Split(delimiterChars, 2);
    
    txtString1.Text = words[0].ToString();
    txtString2.Text = words[1].ToString();
    
    0 讨论(0)
提交回复
热议问题