简体   繁体   中英

Check for specific letter in string

I am trying to check if the first letter in a string is l, the l can be upper or lower case, if it is an l I want to trim it from the string and I am currently using this code to do it

String firstLetter = result.Text[0].ToString();
if (result.Text.Length == 18)
{
    if (firstLetter.Equals("l".ToString()) || firstLetter.Equals("L".ToString()))
    {
        result.Text.Remove(0, 1);
    }
    if (firstLetter == "l" || firstLetter == "L" || firstLetter == "1")
    {
        result.Text.Remove(0, 1);
    }
    if (result.Text.StartsWith("l".ToString()) || result.Text.ToUpper().StartsWith("L".ToString()))
    {
           result.Text.Remove(0, 1);
    }
}

none of these if statements have worked, they are completely skipped over, why arent they working?

All you need to do is:

result = result.TrimStart({'L', 'l'});

This will take "Llama" and make it "ama". If you are trying to take "Llama" and get "lama", use this code:

result = result.ToUpper().StartsWith("L") ? result.Remove(0,1) : result;

If your .Text[] isn't exaclty 18 then it won't go in there.

Once you get the text out of whatever your result is just do this.

if (firstLetter.Substring(0, 1).ToUpper() == "L")
        {
            // equals l so lets remove it
            firstLetter = firstLetter.Remove(0, 1);
        }

You should try this:

bool isFirstL = firstLetter.Substring(0, 1).ToUpper().Equals("L");

And you can use this expression in the way you want, not to assign value for bool.

BTW. you have line if (result.Text.Length == 18) does your string really contains 18 characters?

我必须做:

result = result.TrimStart(new char[] {'L', 'l'});

In C# the string type is designed to be immutable, meaning that you cannot change a string instance. This is from the documentation of the Remove method , emphasis mine:

Returns a new string in which a specified number of characters in the current instance beginning at a specified position have been deleted.

So to actually see the result of the call to Remove, you will have to assign it to something, for example:

result.Text = result.Text.Remove(0, 1);

To see if the string starts with an L, the cleanest way would be to use StartsWith . The entire code would like this:

if (result.Text.Length == 18 &&
    result.Text.StartsWith("L", StringComparison.OrdinalIgnoreCase))
{
    result.Text = result.Text.Remove(0, 1);
}

Just use string.IndexOf , which takes IgnoreCase parameter, like:

string firstLetter = "LlSomething";
if (firstLetter.IndexOf("l", StringComparison.InvariantCultureIgnoreCase) == 0 
        && firstLetter.Length > 0)
{
    firstLetter = firstLetter.Substring(1);
}

and you will get lSomething as the output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM