字符串的 EndsWith()
方法用于检查字符串是否以指定的字符串结尾。
示例
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string text = "Ice cream";
// checks if text ends with cream
bool result = text.EndsWith("cream");
Console.WriteLine(result);
Console.ReadLine();
}
}
}
// Output: True
EndsWith() 语法
字符串 EndsWith()
方法的语法是:
EndsWith(string value, StringComparison comparisonType)
在这里,EndsWith()
是 String
类的一个方法。
EndsWith() 参数
EndsWith()
方法接受以下参数:
- value - 要与给定字符串末尾的子字符串进行比较的字符串。
- comparisonType - 确定如何比较给定字符串和 value。
EndsWith() 返回值
EndsWith()
方法返回:
- True - 如果字符串以给定的字符串结尾。
- False - 如果字符串不是以给定的字符串结尾。
示例 1:C# String EndsWith()
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string text = "Chocolate";
bool result;
// checks if text ends with late
result = text.EndsWith("late");
Console.WriteLine("Ends with late: " + result);
// checks if text ends with gate
result = text.EndsWith("gate");
Console.WriteLine("Ends with gate: " + result);
Console.ReadLine();
}
}
}
输出
Ends with late: True Ends with gate: False
这里,
text.EndsWith("late")
- 返回True
,因为 text 以"late"
结尾。text.EndsWith("gate")
- 返回False
,因为 text 以"gate"
结尾。
示例 2:C# String EndsWith() - 区分大小写
EndsWith()
方法是区分大小写的。但是,我们也可以忽略或考虑字母的大小写。
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string text = "Ice cream";
bool result;
// ignores case
result = text.EndsWith("Cream", StringComparison.OrdinalIgnoreCase);
Console.WriteLine("Ends with Cream: " + result);
// considers case
result = text.EndsWith("Cream", StringComparison.Ordinal);
Console.WriteLine("Ends with Cream: " + result);
Console.ReadLine();
}
}
}
输出
Ends with Cream: True Ends with Cream: False
这里,
StringComparison.OrdinalIgnoreCase
- 忽略字母的大小写。StringComparison.Ordinal
- 考虑字母的大小写。