I have a variable that contains text from a textbox.

a = textBox1.Text;9 

Then there is a small method that counts the number of letters in a string and displays this value in label1

  Console.Write(a.Length); label1.Text = Convert.ToString(a.Length); 

I need this program: 1. I did not count all the letters in the string, but counted them up to a space. 2. Saved the result before the space and after it in different variables.

Please help me at least point 1, but with the possibility of further upgrade to point 2

    3 answers 3

    It is possible so:

     var array = a.Split(' '); // разбиваем исходную строку на подстроки разделителем пробел var part1 = array[0]; var part2 = array[1]; var len = part1.Length; label1.Text = Convert.ToString(len); 

    You will need to independently handle the situation when there is no space in the string.

    • In theory, you need a.Split(new[] { ' ' }, 2) , and then suddenly there are a lot of spaces in the line. - VladD
    • @VladD depends on the task :) you can do it like this - pavelip

    Probably you need something like this.

     using System; class Program { static void Main(string[] args) { string s = "Hello, World!"; string s1, s2; int n; if ((n = s.IndexOf(' ')) != -1) { s1 = s.Substring(0, n); s2 = s.Substring(n + 1); } else { s1 = s; s2 = ""; } Console.WriteLine("s1 = \"{0}\" with length = {1}, s2 = \"{2}\" with length {3}", s1, s1.Length, s2, s2.Length); } } 

    The output of the program to the console:

     s1 = "Hello," with length = 6, s2 = "World!" with length 6 
    • You can do without string.Copy. The lines are immutable) - pavelip
    • @pavelip Yes, by inertia wrote. - Vlad from Moscow
    • @VladfromMoscow Thanks, but how to make the last line appear not in the console but in label1? - hello_max
    • @hello_max Probably just write label1.Text = s2; - Vlad from Moscow

    You can do this: int count = a.indexOf(" ");

    • Try to write more detailed answers. Explain what is the basis of your statement? - Nicolas Chabanovsky