简体   繁体   中英

How to check the last character of a string in C#?

I want to find the last character of a string and then put in an if<\/code> stating that if the last character is equal to "A", "B" or "C" then to do a certain action. How do I get the last character?

"

Use the endswith method of strings:

if (string.EndsWith("A") || string.EndsWith("B"))
{
    //do stuff here
}

Heres the MSDN article explaining this method:

http://msdn.microsoft.com/en-us/library/system.string.endswith(v=vs.71).aspx

I assume you don't actually want the last character position (which would be yourString.Length - 1 ), but the last character itself . You can find that by indexing the string with the last character position:

yourString[yourString.Length - 1]

string is a zero based array of char .

char last_char = mystring[mystring.Length - 1];

Regarding the second part of the question, if the char is A , B , C

Using if statement

char last_char = mystring[mystring.Length - 1];
if (last_char == 'A' || last_char == 'B' || last_char == 'C')
{
    //perform action here
}

Using switch statement

switch (last_char)
{
case 'A':
case 'B':
case 'C':
    // perform action here
    break
}

I like using Linq:

YourString.Last()

You'll need to import the System.Linq namespace if you don't have it already. I wouldn't import the namespace just to use .Last(), though.

There is an index-from-end operator that looks like this: ^n .

var list = new List<int>();

list[^1]  // this is the last element
list[^2]  // the second-to-last element
list[^n]  // etc.

The official documentation about indices and ranges describes this operator.

您还可以通过使用 LINQ 和myString.Last()来获取最后一个字符,尽管这可能比其他答案慢,并且它为您提供char ,而不是string

Since C# 8.0<\/strong> , you can use new syntactic forms for System.Index<\/code> and System.Range<\/code> hence addressing specific characters in a string<\/code> becomes trivial. Example for your scenario:

var lastChar = aString[^1..]; // aString[Range.StartAt(new Index(1, fromEnd: true))

if (lastChar == "A" || lastChar == "B" || lastChar == "C")
    // perform action here

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