Home > Software engineering >  Adding a character at the beginning of a string if it does not exist using LINQ
Adding a character at the beginning of a string if it does not exist using LINQ

Time:02-22

I have a string which I apply some LINQ methods. After applying a Replace, I would like to add a '/' character at the beginning of the resulting string if and only if it does not exists yet.

For example:

string myString = "this is a test";
string newString = myString.Replace(" " , string.Empty).AddCharacterAtBeginingIfItDoesNotExists('/');

So the resulting newString should be:

"/thisisatest"

If character '/' already exists, it is not needed to add it. For example:

string myString = "/this is a test";
string newString = myString.Replace(" " , string.Empty).AddCharacterAtBeginingIfItDoesNotExists('/');

So the resulting newString should be:

"/thisisatest"

CodePudding user response:

You can use String.StartsWith:

public static string AddStringAtBeginningIfItDoesNotExist(this string text, string prepend)
{
    if (text == null) return prepend;
    if (prepend == null) prepend = "";
    return text.StartsWith(prepend) ? text : prepend   text;
}

(allowed string instead of char to be more useful)

  • Related