如何在C#中检查字符串的最后一个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14794267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:00:31  来源:igfitidea点击:

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

c#

提问by esq619

I want to find the last character of a string and then put in an ifstating 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?

我想找到字符串的最后一个字符,然后输入一个if声明,如果最后一个字符等于“A”、“B”或“C”,则执行某个操作。我如何获得最后一个字符?

采纳答案by Unicorno Marley

Use the endswithmethod of strings:

使用endswith字符串的方法:

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

Heres the MSDN article explaining this method:

这是解释此方法的 MSDN 文章:

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

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

回答by icktoofay

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.Length - 1),而是最后一个字符本身。您可以通过使用最后一个字符位置索引字符串来发现:

yourString[yourString.Length - 1]

回答by Parimal Raj

stringis a zero basedarray of char.

string是一个zero based数组char

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

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

关于问题的第二部分,如果字符是A, B,C

Using if statement

使用 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 statement

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

回答by oscilatingcretin

I like using Linq:

我喜欢使用 Linq:

YourString.Last()

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.

如果您还没有 System.Linq 命名空间,则需要导入它。不过,我不会仅仅为了使用 .Last() 而导入命名空间。