Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying a substring using C#

Tags:

substring

c#

If I have a string like SMITH 9-2 #3-10H13 how can I modify the 9-2 to be 09-02 using C#? Another example is RODGER 3-1 #5-11H17 would be RODGER 03-01 #5-11H17. Another is GWIN 10-3 #6-11H12 would be GWIN 10-03 #6-11H12. and so on.. I'm stumped.

like image 558
DaBears Avatar asked Feb 13 '26 15:02

DaBears


1 Answers

Here's a way to do it using Split and Join:

string str = "SMITH 9-2 #3-10H13";
string[] parts = str.Split(' ');
string[] numbers = parts[1].Split('-');
parts[1] = string.Join("-", numbers.Select(x => x.PadLeft(2, '0')));
string result = string.Join(" ", parts);
like image 51
Meta-Knight Avatar answered Feb 15 '26 05:02

Meta-Knight



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!