Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a character at the beginning of a string if it does not exist using LINQ

Tags:

c#

linq

.net-4.5

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"

like image 397
Ralph Avatar asked Sep 18 '25 02:09

Ralph


1 Answers

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)

like image 179
Tim Schmelter Avatar answered Sep 19 '25 17:09

Tim Schmelter