C# 字符串 - EndsWith() 方法
C# 字符串的 EndsWith() 方法用于检查此字符串是否以指定的字符串/字符结尾。
如果值为 null,此方法将抛出 ArgumentNullException。
语法
以下是 C# 字符串的语法 EndsWith() 方法 -
public bool EndsWith (char/string value);
参数
此方法仅接受一个参数,可以是字符或字符串。它将字符与此对象末尾的字符进行比较,或将字符串与此对象末尾的子字符串进行比较。
返回值
如果值与此对象或实例的末尾匹配,则此方法返回true;否则,返回false。
示例 1:检查字符
以下是EndsWith()方法的基本示例,用于检查指定字符是否位于字符串末尾 -
using System;
class Program {
static void Main() {
string str = "Hello, tutorialspoint";
bool res = str.EndsWith('t');
Console.WriteLine(res);
}
}
输出
以下是输出 -
True
示例 2:检查字符串
让我们看一下 EndsWith() 方法的另一个示例。在这里,我们检查字符串是否位于字符串的末尾 -
using System;
class Program {
static void Main() {
string str = "Hello, tutorialspoint";
bool res = str.EndsWith("point");
Console.WriteLine("The string is available at the end: " + res);
}
}
输出
以下是输出 -
The string is available at the end: True
示例 3:如果字符不在字符串末尾
在本例中,我们使用 EndsWith() 方法检查字符串末尾是否存在字符。如果不存在,则此方法返回 false −
using System;
class Program {
static void Main() {
string str = "Hello, tutorialspoint";
bool res = str.EndsWith('P');
Console.WriteLine("The character is available at the end: " + res);
}
}
输出
以下是输出 -
The character is available at the end: False
示例 4:如果字符串以特定子字符串结尾
以下示例使用条件语句,当字符串以特定子字符串结尾时显示语句 -
using System;
class Program {
static void Main() {
string str = "Hello, tutorialspoint";
bool res = str.EndsWith("spoint");
Console.Write(res == true
? "The specified string is available in this string"
: "The specified string is not available in the string");
}
}
输出
以下是输出 -
The specified string is available in this string

csharp_strings.html