Reputation:
I have a file in C# which has keywords like this each present on new line
1234-hello I am here
121-Where are you
I want to read the file and write 1234-Hello
121-Where
into another file, I have found lot of codes on internet that are based on comma seperated but couldn't find code to extract values on the basis of new line.
The -
seperates the Number and the keyword I want to extract, like 1234-hello
Upvotes: 2
Views: 119
Reputation: 7773
You can use this:
string[] lines = File.ReadAllLines(path);
for(int i = 0; i < lines.Length; i++)
{
string line = lines[i];
string[] tokens = line.Split(new char[]{'-', ' '});
int number = int.Parse(tokens[0]);
string text = tokens[1];
lines[i] = number + "-" + text;
}
File.WriteAllLines(path2, lines);
You probably want to add some error handling
Upvotes: 4
Reputation: 101701
First read all lines, Split
each line by white-space, get the first part and write the content to the new file:
var lines = File.ReadLines("path").Select(x => x.Split().First());
File.WriteAllLines("otherPath", lines);
This code should produce an output like this:
1234-Hello
121-Where
Upvotes: 2