Reputation: 1460
I have a text file containing these words:
Name: Bob
Age: 3
and my c# code is:
string text = File.ReadAllText("path to a.txt");
How do i substring this so that i could get the value 3
and Bob
?
Upvotes: 1
Views: 981
Reputation: 117154
Assuming that you're reading your data from a file, then this should work nicely:
Dictionary<string, string> pairs =
File
.ReadAllLines(@"50780830.txt")
.Select(l => l.Split(':'))
.Where(xs => xs.Length == 2)
.Where(xs => !String.IsNullOrEmpty(xs[0].Trim()))
.ToDictionary(xs => xs[0].Trim(), xs => xs[1].Trim());
Console.WriteLine(pairs["Name"]);
Console.WriteLine(pairs["Age"]);
When I run this I get:
Bob 3
Upvotes: 6
Reputation: 526
You can try this with only one line:
IEnumerable<String> list = str.Split('\n').Select(s => s.Split(':')[1]);
The first split meaning is to isolate each row. The second split meaning is to take the word after ':'.
Upvotes: 0
Reputation: 2729
You can achieve this by using Split and Substring
function just like this:
String str = "Name: Bob\r\n\r\nAge: 32";
String Name = str.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)[0];
Name = Name.Substring(Name.IndexOf(':') + 1).Trim();
String Age = str.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)[1];
Age = Age.Substring(Age.IndexOf(':') + 1).Trim();
Console.WriteLine(Name + "," + Age);
Upvotes: 1