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
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
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; 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.
Source: https://ru.stackoverflow.com/questions/575223/
All Articles