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

问题描述 投票:0回答:7

我想在 C# 中找到字符串的最后一个字符,然后将其放入

if
语句中。

然后,如果最后一个字符等于“A”、“B”或“C”,则应执行特定操作。

如何在 C# 中获取字符串的最后一个字符?

c# string char
7个回答
102
投票

使用字符串的

EndsWith()
方法:

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

以下 MSDN 文章解释了此方法:

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


20
投票

我假设您实际上并不想要最后一个字符位置

yourString.Length - 1
),而是最后一个字符本身。您可以通过使用最后一个字符位置索引字符串来找到这一点:

yourString[yourString.Length - 1]

12
投票

string
zero based
char
数组。

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

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

A
B
C

使用

if statement

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

使用

switch statement

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

9
投票

有一个 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.

有关索引和范围的官方文档描述了此运算符。需要注意的一件事是:如果列表中没有足够的元素,则该运算符可能会在运行时失败 (

System.ArgumentOutOfRangeException
)。


3
投票

在最新的 C# 版本中,只需在 C# 中的字符串上使用

Last()
LastOrDefault()
即可返回最后一个字符。

string sample = "sample string";
char lastCharacter = sample.Last(); 
if (lastCharacter == 'A' || lastCharacter == 'B' || lastCharacter == 'C') 
{
     Console.WriteLine(lastCharacter);
}
else if (lastCharacter == 'g')
{
     Console.WriteLine($"found! {char.ToUpper(lastCharacter)}");
}
else if (sample.EndsWith("ing"))
{
     Console.WriteLine($"use for multiple characters! {sample}");
}

2
投票

C# 8.0 起,您可以对

System.Index
System.Range
使用新的语法形式,因此处理
string
中的特定字符变得微不足道。您的场景示例:

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

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

此处有完整说明:Ranges(Microsoft Docs)


0
投票

您还可以使用 LINQ 和

myString.Last()
来获取最后一个字符,尽管这可能比其他答案慢,并且它会给您一个
char
,而不是
string

© www.soinside.com 2019 - 2024. All rights reserved.