在C#中,string 类是 System 命名空间中非常基础且广泛使用的类,提供了多种方法来操作字符串。以下是一些常用的 string API:
Length/Length - 获取字符串的长度:
int length = "Hello World".Length;
Substring(int startIndex) - 返回字符串的子字符串,从指定的起始索引直到字符串的末尾:
string sub = "Hello World".Substring(0, 5); // "Hello"
Substring(int startIndex, int length) - 返回字符串的子字符串,从指定的起始索引开始,指定长度的字符数:
string sub = "Hello World".Substring(6, 5); // "World"
IndexOf(string value) - 返回子字符串在原始字符串中首次出现的索引位置:
int index = "Hello World".IndexOf("World"); // 6
LastIndexOf(string value) - 返回子字符串在原始字符串中最后一次出现的索引位置:
int lastIndex = "Hello World".LastIndexOf("l"); // 9
Contains(string value) - 检查字符串是否包含指定的子字符串:
bool contains = "Hello World".Contains("World"); // true
StartsWith(string value) - 检查字符串是否以指定的子字符串开始:
bool startsWith = "Hello World".StartsWith("Hello"); // true
EndsWith(string value) - 检查字符串是否以指定的子字符串结束:
bool endsWith = "Hello World".EndsWith("World"); // true
Replace(string oldValue, string newValue) - 替换字符串中的所有匹配子字符串为新的子字符串:
string replaced = "Hello World".Replace("World", ".NET"); // "Hello .NET"
Remove(int startIndex, int count) - 移除字符串中从指定索引开始的特定数量的字符:
string removed = "Hello World".Remove(6, 5); // "Hello "
PadLeft(int totalWidth) - 用空格填充字符串的开头,直到字符串的总长度达到指定的宽度:
string paddedLeft = "Hello".PadLeft(10); // " Hello"
PadRight(int totalWidth) - 用空格填充字符串的末尾,直到字符串的总长度达到指定的宽度:
string paddedRight = "Hello".PadRight(10); // "Hello "
Trim() - 移除字符串两端的空白字符:
string trimmed = " Hello World ".Trim(); // "Hello World"
ToLower()/ToUpper() - 将字符串转换为全部小写/大写:
string lower = "HELLO WORLD".ToLower(); // "hello world"
string upper = "hello world".ToUpper(); // "HELLO WORLD"
Split(separator) - 通过指定的分隔符将字符串分割成字符串数组:
string[] parts = "One,Two,Three".Split(','); // parts = [ "One", "Two", "Three" ]
Concat(string str0, string str1, … ) - 连接多个字符串:
string concat = string.Concat("Hello", " ", "World"); // "Hello World"
Format(IFormatProvider provider, string format, …) - 使用占位符格式化字符串:
string formatted = string.Format("Hello {0}!", "World"); // "Hello World!"
Insert(int index, string value) - 在指定索引处插入一个字符串:
string inserted = "Hello World".Insert(5, " at "); // "Hello at World"
Equals(string value) - 比较两个字符串是否相等:
bool equals = "Hello".Equals("hello"); // false, 区分大小写
CompareTo(string str) - 比较当前字符串与另一个字符串的顺序:
int result = "Hello".CompareTo("World"); // 结果为小于0,等于0或大于0
想了解更多游戏开发知识,可以扫描下方二维码,免费领取游戏开发4天训练营课程