C# String StartsWith() 字符串开头检查方法
字符串 StartsWith()
方法检查字符串是否以指定的字符串开头。
示例
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Icecream";
bool result;
// 检查 "Icecream" 是否以 "Ice" 开头
result = str.StartsWith("Ice");
Console.WriteLine(result);
Console.ReadLine();
}
}
}
// 输出:True
StartsWith() 语法
字符串 StartsWith()
方法的语法是:
StartsWith(String value, StringComparison comparisonType)
这里,StartsWith()
是 String
类的一个方法。
StartsWith() 参数
StartsWith()
方法接受以下参数:
- value - 要比较的字符串
- comparisonType - 决定如何比较给定的字符串和值。
StartsWith() 返回值
StartsWith()
方法返回:
- True - 如果字符串以
value
开头 - False - 如果字符串不以
value
开头
示例 1:C# 字符串 StartsWith()
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Icecream";
bool result;
// 检查 "Icecream" 是否以 "I" 开头
result = str.StartsWith("I");
Console.WriteLine("以 I 开头: " + result);
// 检查 "Icecream" 是否以 "i" 开头
result = str.StartsWith("i");
Console.WriteLine("以 i 开头: " + result);
Console.ReadLine();
}
}
}
输出
以 I 开头: True
以 i 开头: False
示例 2:C# 字符串 StartsWith() 带 comparisonType
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Icecream";
bool result;
// 考虑字母大小写
result = str.StartsWith("ice", StringComparison.InvariantCulture);
Console.WriteLine("以 ice 开头: " + result);
// 忽略字母大小写
result = str.StartsWith("ice", StringComparison.InvariantCultureIgnoreCase);
Console.WriteLine("以 ice 开头: " + result);
Console.ReadLine();
}
}
}
输出
以 ice 开头: False
以 ice 开头: True
这里,
StringComparison.InvariantCulture
- 考虑字母大小写StringComparison.InvariantCultureIgnoreCase
- 忽略字母大小写