I enter the line with the command:

string[] n = Console.ReadLine().Split(' '); // int a = int.Parse(n[0]); string b = (n[1]); 

But then there will be a space between the digit and the letter, but without it

  • Just enter without a space and that's it. - Vladimir Martyanov

3 answers 3

If I understand your question correctly, you want to enter a number and a string without a space, and take the result apart, right? (Because otherwise your code just waits for a space, and divides the input into parts by it.)

Assuming that this is the case, the easiest way is probably to manually calculate the indices:

 var s = Console.ReadLine(); int idx = 0; while (idx < s.Length && char.IsDigit(s[idx])) idx++; if (idx == 0 || idx == s.Length) throw new FormatException(); var num = int.Parse(s.Substring(0, idx)); var text = s.Substring(idx); 

    If you want to enter a number and a string without a space (something like 32hello ), you can try to use regulars:

     Regex reg = new Regex(@"(\d+)([^\d\s]+)"); string str = Console.ReadLine(); var m = reg.Match(str); int i = int.Parse(m.Groups[1].Value); string s = m.Groups[2].Value; 
    1. Regular expressions in the .NET Framework
    2. Regular Expression Language Elements - Quick Reference
        public static void Main(string[] args) { Console.WriteLine("Введите данные:"); var s = Console.ReadLine(); string resultN = string.Empty; string resultS = string.Empty; foreach (char c in s) { if (Char.IsDigit(c)) { resultN += c.ToString(); } else { resultS += c.ToString(); } } int i = 0; Console.Write("\nЧисло: " + resultN + "\n" + "Символы: " + resultS + "\n\n"); if (int.TryParse(resultN, out i)) { Console.WriteLine("Парсинг числа: " + i.ToString()); } Console.ReadKey(true); } 

      PS About StringBuider in the course, yes. Did not complicate things. And yes, it will process only the input of positive integers, but if necessary, the “-” input check is easy to add.

      • one
        enter "1a2b3c", what will be the output? - "123" and "abc". I'm not sure that this is the desired and expected result. It is worth correcting the proposed solution. And practical advice - test what you offer if you are not sure for 300% of correctness. - rdorn