C# String EndsWith() 字符串结尾检查方法
String的EndsWith()
方法检查字符串是否以指定的字符串结尾。
示例
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string text = "冰淇淋";
// 检查text是否以"淇淋"结尾
bool result = text.EndsWith("淇淋");
Console.WriteLine(result);
Console.ReadLine();
}
}
}
// 输出: 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 = "巧克力";
bool result;
// 检查text是否以"克力"结尾
result = text.EndsWith("克力");
Console.WriteLine("以克力结尾: " + result);
// 检查text是否以"门"结尾
result = text.EndsWith("门");
Console.WriteLine("以门结尾: " + result);
Console.ReadLine();
}
}
}
输出
以克力结尾: True
以门结尾: False
在这里,
text.EndsWith("克力")
- 返回True
,因为text
以"克力"
结尾text.EndsWith("门")
- 返回False
,因为text
不以"门"
结尾
示例2:C# String EndsWith() - 大小写敏感性
EndsWith()
方法是大小写敏感的。但是,我们也可以忽略或考虑字母大小写。
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string text = "冰淇淋";
bool result;
// 忽略大小写
result = text.EndsWith("淇淋", StringComparison.OrdinalIgnoreCase);
Console.WriteLine("以淇淋结尾: " + result);
// 考虑大小写
result = text.EndsWith("淇淋", StringComparison.Ordinal);
Console.WriteLine("以淇淋结尾: " + result);
Console.ReadLine();
}
}
}
输出
以淇淋结尾: True
以淇淋结尾: False
在这里,
StringComparison.OrdinalIgnoreCase
- 忽略大小写StringComparison.Ordinal
- 考虑大小写