Search code examples
c#stringprefix

Add prefix in string if missing in c#


I have below multiple transaction passing to transaction string:

string transaction = "12345,56789";

I want check that if that transaction having prefix '0' so how to check that.

e.g.

"012345,056789";

Suppose if these transactions don't have prefix '0' like "12345,56789" I want add prefix like this one "012345,056789".

I tried with below code it's wont working for me can any one please guide me how to achieve that.

    if(transaction.StartsWith("0"))
    {
        transaction = transaction;
    }
    else
    {
        transaction = "0" + transaction;
    }

Solution

  • If you want to check each numeric part of the string, i.e.

     "12345,56789"    =>   "012345,056789"
     "012345,56789"   =>   "012345,056789"
     "12345,056789"   =>   "012345,056789"
     "012345,056789"  =>   "012345,056789"
    

    You can Split the transaction, check each part and, finally, Join these parts back:

    using System.Linq;
    
    ...
    
    transaction = string.Join(",", transaction
      .Split(',')
      .Select(part => part.StartsWith("0") ? part : $"0{part}"));
    

    Another possibility is regular expressions:

     using System.Text.RegularExpressions;
    
     ...
    
     transaction = Regex.Replace(transaction, @"\b[1-9]", "0$&");
    

    Here we match every leftmost digit (if it's in 1..9 range) for each part (note \b for word border) and add 0 prefix: in "0$&" 0 is 0 and $& stands for the entire match.