字符串 StartsWith()
方法用于检查字符串是否以指定的字符串开头。
示例
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Icecream";
bool result;
// checks if "Icecream" starts with "Ice"
result = str.StartsWith("Ice");
Console.WriteLine(result);
Console.ReadLine();
}
}
}
// Output: 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;
// checks if "Icecream" starts with "I"
result = str.StartsWith("I");
Console.WriteLine("Starts with I: " + result);
// checks if "Icecream" starts with "i"
result = str.StartsWith("i");
Console.WriteLine("Starts with i: " + result);
Console.ReadLine();
}
}
}
输出
Starts with I: True Starts with i: False
示例 2:C# 字符串 StartsWith()(带 comparisonType)
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Icecream";
bool result;
// considers letter case
result = str.StartsWith("ice", StringComparison.InvariantCulture);
Console.WriteLine("Starts with ice: " + result);
// ignores letter case
result = str.StartsWith("ice", StringComparison.InvariantCultureIgnoreCase);
Console.WriteLine("Starts with ice: " + result);
Console.ReadLine();
}
}
}
输出
Starts with ice: False Starts with ice: True
这里,
StringComparison.InvariantCulture
- 考虑字母大小写StringComparison.InvariantCultureIgnoreCase
- 忽略字母大小写