Suppose there is a text file in which there is a word and a sequence of numbers in each line. How can I put words on one line and numbers only on another?

Sample file:

testText0 1 2 3 4 testText1 2 4 
  • That is, you are guaranteed letters, then a space, then numbers on each line? Or maybe something else? Give an example of the text. - VladD
  • testText0 1 2 3 4 testText1 2 4 (by line) - Draktharon

2 answers 2

In addition to making head-on, there is always the option of using regular expressions .

 using System.Text.RegularExpressions; ........ var Lines = File.ReadAllLines("MyFileName.txt"); var RegEx = new Regex(@"^([a-zA-Z]+)([\d\s]+)$"); var Words = new List<String>(); var Digits = new List<String>(); foreach (var Line in Lines){ var Matches = RegEx.Match(Line); Words.Add(Matches.Groups[1].ToString()); Digits.Add(Matches.Groups[2].ToString()); } 

This approach is also good because it automatically validates the input data.

Check regular expressions here .

    Well, for example, something like this:

     var digits = "0123456789".ToArray(); var lines = File.ReadLines(path); var linesWithBreakingIndices = lines.Select(line => new { line, index = line.IndexOfAny(digits) }).ToList(); var justWords = string.Join(" ", linesWithBreakingIndices.Select(li => li.line.Substring(0, li.index))); var justDigits = string.Join(" ", linesWithBreakingIndices.Select(li => li.line.Substring(li.index))); 

    Option without LINQ:

     var digits = "0123456789".ToArray(); var lines = File.ReadLines(path); StringBuilder justWordsBuilder = new StringBuilder(), justDigitsBuilder = new StringBuilder(); var first = true; foreach (var line in lines) { var index = line.IndexOfAny(digits); if (!first) { justWordsBuilder.Append(' '); justDigitsBuilder.Append(' '); } justWordsBuilder.Append(line, 0, index); justDigitsBuilder.Append(line, index, line.Length - index); first = false; } var justWords = justWordsBuilder.ToString(); var justDigits = justDigitsBuilder.ToString(); 
    • thanks, really LINQ don't know yet, but I'll try to figure it out - Draktharon
    • @ RustemValeev: Added option without LINQ. But you still learn LINQ, without it anywhere. - VladD