简体   繁体   English

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

[英]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.我想找到一个字符串的最后一个字符,然后输入一个if<\/code>语句,如果最后一个字符等于“A”、“B”或“C”,则执行某个操作。 How do I get the last character?我如何获得最后一个字符?

"

Use the endswith method 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

I assume you don't actually want the last character position (which would be yourString.Length - 1 ), but the last character itself .我假设您实际上并不想要最后一个字符的位置(这将是yourString.Length - 1 ),而是最后一个字符本身 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 . string是一个zero basedchar数组。

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
}

I like using Linq: 我喜欢使用Linq:

YourString.Last()

You'll need to import the System.Linq namespace if you don't have it already. 如果您还没有它,则需要导入System.Linq命名空间。 I wouldn't import the namespace just to use .Last(), though. 但是我不会导入命名空间只是为了使用.Last()。

There is an index-from-end operator that looks like this: ^n .有一个index-from-end 运算符,如下所示: ^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.C# 8.0<\/strong>开始,您可以对System.Index<\/code>和System.Range<\/code>使用新的语法形式,因此处理字符串中的特定string<\/code>变得微不足道。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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