string manipulation in c#

riyabansal

New member
Joined
Nov 15, 2022
Messages
1
Programming Experience
Beginner
i want to fetch " Name Date Value BP 01/26/2015 15 Ht 01/26/2015 15 Wt 01/26/2015 70 BMI 01/26/2015 218.71 " date and value from this string.
how can i achieve this.

Thanks in advance.
 
What have you tried and where are you stuck? If you want to manipulate a string then you should learn about string manipulation in general, then apply the principles to your specific scenario. What do you understand and not understand about string manipulation, what have you tried to apply to this problem and what happened when you tried it?
 
Coding crossword #18664 ? :)

Could use regex:

C#:
var str = " Name  Date Value BP 01/26/2015 15 Ht 01/26/2015 15    Wt 01/26/2015 70  BMI 01/26/2015 218.71  ";
var rex = new Regex(@"(?<dt>\d\d/\d\d/\d{4}) (?<v>\d+(\.\d+)?)");

var mc = rex.Matches(str);
foreach(Match m in mc){
  Console.WriteLine($"Date: {m.Groups["dt"].Value}, Val: {m.Groups["v"]}");
}
The regex matches the date into a capturing group called dt, and the value as either N or N.N onto a group called v, then digs them out in a loop

---

Could also use arrays and relative indexing for those "its' a problem! gotta use LINQ!" types:

C#:
var str = " Name  Date Value BP 01/26/2015 15 Ht 01/26/2015 15    Wt 01/26/2015 70  BMI 01/26/2015 218.71  ";

var bits = str.Split();
     
foreach(var t in bits.Select((E,I) => (E,I)).Where(t => t.E.Contains("/"))){
  Console.WriteLine($"Date: {t.E}, Val: {bits[t.I+1]}");
}

We yank the things that look like dates (contains "/") and their index, and then use the index+1 to retrieve the associated value from the original array

---

Or for our normal viewers:

C#:
var str = " Name  Date Value BP 01/26/2015 15 Ht 01/26/2015 15    Wt 01/26/2015 70  BMI 01/26/2015 218.71  ";

var bits = str.Split();
     
for(int i = 0; i < bits.Length, i++){
  if(bits[i].Contains("/")) {
    Console.WriteLine($"Date: {bits[i]}, Val: {bits[i+1]}");
  }
}

More grok'ably (IMHO) than either of the above, we split the array on spaces, then loop it with a normal loop that allows us to get the i'th and i+1'th element if the i'th contains a /
 
Last edited:
If i is bits.Length - 1, then bits + 1 will overrun the the bits array.
 
True.. It won't in that example but it wouldn't hurt to make the loop condition < Length-1
 
Last edited:

Latest posts

Back
Top Bottom