C# 字符串常用方法

文章目录

  • 前言
  • Length:获取字符串中字符的个数(不包括末尾的空字符)
  • [ToLower() 和 ToUpper():将字符串转换为小写或大写形式](#ToLower() 和 ToUpper():将字符串转换为小写或大写形式)
  • [Substring(int startIndex, int length):从指定索引开始截取指定长度的子字符串](#Substring(int startIndex, int length):从指定索引开始截取指定长度的子字符串)
  • [Remove(int startIndex, int length):从指定索引开始移除指定长度的字符](#Remove(int startIndex, int length):从指定索引开始移除指定长度的字符)
  • [Replace(string oldValue, string newValue):替换字符串中的指定字符或子字符串](#Replace(string oldValue, string newValue):替换字符串中的指定字符或子字符串)
  • [Split(char\[\] separator, StringSplitOptions options) :根据指定的分隔符拆分字符串](#Split(char[] separator, StringSplitOptions options) :根据指定的分隔符拆分字符串)
  • [IndexOf(char value) 和 IndexOf(string value):查找指定字符或子字符串在字符串中第一次出现的位置](#IndexOf(char value) 和 IndexOf(string value):查找指定字符或子字符串在字符串中第一次出现的位置)
  • [LastIndexOf(char value) 和 LastIndexOf(string value):查找指定字符或子字符串在字符串中最后一次出现的位置](#LastIndexOf(char value) 和 LastIndexOf(string value):查找指定字符或子字符串在字符串中最后一次出现的位置)
  • [Trim()、TrimStart() 和 TrimEnd():移除字符串开头、结尾或两端的空白字符(包括空格、制表符和换行符)](#Trim()、TrimStart() 和 TrimEnd():移除字符串开头、结尾或两端的空白字符(包括空格、制表符和换行符))
  • [Contains(string value):判断字符串是否包含指定的子字符串](#Contains(string value):判断字符串是否包含指定的子字符串)
  • [StartsWith(string value) 和 EndsWith(string value):判断字符串是否以指定的子字符串开始或结束](#StartsWith(string value) 和 EndsWith(string value):判断字符串是否以指定的子字符串开始或结束)
  • [PadLeft(int totalWidth) 和 PadRight(int totalWidth):在字符串的左侧或右侧填充空格,直到达到指定的总宽度](#PadLeft(int totalWidth) 和 PadRight(int totalWidth):在字符串的左侧或右侧填充空格,直到达到指定的总宽度)
  • [Join(string separator, params string\[\] values):将多个字符串连接成一个字符串,并使用指定的分隔符分隔它们](#Join(string separator, params string[] values):将多个字符串连接成一个字符串,并使用指定的分隔符分隔它们)
  • [Format(string format, params object\[\] args):格式化字符串,将指定的参数插入到格式字符串中](#Format(string format, params object[] args):格式化字符串,将指定的参数插入到格式字符串中)
  • [IsNullOrEmpty(string value):判断字符串是否为空或null](#IsNullOrEmpty(string value):判断字符串是否为空或null)
  • [IsNullOrWhiteSpace(string value):判断字符串是否为空、null或仅包含空白字符](#IsNullOrWhiteSpace(string value):判断字符串是否为空、null或仅包含空白字符)
  • [Concat(params string\[\] values):连接多个字符串并返回一个新的字符串](#Concat(params string[] values):连接多个字符串并返回一个新的字符串)
  • [CopyTo(int sourceIndex, char\[\] destination, int destinationIndex, int count):将字符串中的字符复制到指定的字符数组中](#CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count):将字符串中的字符复制到指定的字符数组中)
  • [IndexOfAny(char\[\] anyOf) 和 LastIndexOfAny(char\[\] anyOf):查找字符数组中字符在字符串中第一次或最后一次出现的位置](#IndexOfAny(char[] anyOf) 和 LastIndexOfAny(char[] anyOf):查找字符数组中字符在字符串中第一次或最后一次出现的位置)
  • [PadLeft(int totalWidth, char paddingChar) 和 PadRight(int totalWidth, char paddingChar):在字符串的左侧或右侧填充指定的字符,直到达到指定的总宽度](#PadLeft(int totalWidth, char paddingChar) 和 PadRight(int totalWidth, char paddingChar):在字符串的左侧或右侧填充指定的字符,直到达到指定的总宽度)
  • [Remove(int startIndex):从指定索引开始移除字符串的剩余部分](#Remove(int startIndex):从指定索引开始移除字符串的剩余部分)
  • [Insert(int startIndex, string value):在指定索引处插入一个字符串](#Insert(int startIndex, string value):在指定索引处插入一个字符串)
  • [字符串插值(String Interpolation)(C# 6.0及更高版本):使用符号和大括号{}来嵌入变量或表达式,从而创建格式化的字符串](# 6.0及更高版本):使用符号和大括号{}来嵌入变量或表达式,从而创建格式化的字符串)

前言

请注意,C#中的string是不可变的,这意味着每次对字符串进行操作时,都会返回一个新的字符串对象,而原始字符串不会被修改。


Length:获取字符串中字符的个数(不包括末尾的空字符)

csharp 复制代码
string str = "Hello";
Console.WriteLine(str.Length); // 输出 5

ToLower() 和 ToUpper():将字符串转换为小写或大写形式

csharp 复制代码
string str = "Hello";  
Console.WriteLine(str.ToLower()); // 输出 "hello"  
Console.WriteLine(str.ToUpper()); // 输出 "HELLO"

Substring(int startIndex, int length):从指定索引开始截取指定长度的子字符串

csharp 复制代码
string str = "Hello World"; 
Console.WriteLine(str.Substring(6, 5)); // 输出 "World"

Remove(int startIndex, int length):从指定索引开始移除指定长度的字符

csharp 复制代码
string str = "Hello World"; 
Console.WriteLine(str.Remove(6, 5)); // 输出 "Hello "

Replace(string oldValue, string newValue):替换字符串中的指定字符或子字符串

csharp 复制代码
string str = "Hello World";  
Console.WriteLine(str.Replace('o', '0')); // 输出 "Hell0 W0rld"  
Console.WriteLine(str.Replace("World", "C#")); // 输出 "Hello C#"

Split(char\[\] separator, StringSplitOptions options) :根据指定的分隔符拆分字符串

csharp 复制代码
string str = "Hello,World,C#";  
string[] parts = str.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);  
foreach (string part in parts)  
{  
    Console.WriteLine(part); // 输出 "Hello" "World" "C#"  
}

IndexOf(char value) 和 IndexOf(string value):查找指定字符或子字符串在字符串中第一次出现的位置

csharp 复制代码
string str = "Hello World";  
Console.WriteLine(str.IndexOf('W')); // 输出 6  
Console.WriteLine(str.IndexOf("World")); // 输出 6

LastIndexOf(char value) 和 LastIndexOf(string value):查找指定字符或子字符串在字符串中最后一次出现的位置

csharp 复制代码
string str = "abc abc abc";  
Console.WriteLine(str.LastIndexOf('a')); // 输出 9(最后一个 'a' 的位置)  
Console.WriteLine(str.LastIndexOf("abc")); // 输出 9(最后一个 "abc" 的位置)

Trim()、TrimStart() 和 TrimEnd():移除字符串开头、结尾或两端的空白字符(包括空格、制表符和换行符)

csharp 复制代码
string str = "   Hello World   ";  
Console.WriteLine(str.Trim()); // 输出 "Hello World"  
Console.WriteLine(str.TrimStart()); // 输出 "Hello World   "  
Console.WriteLine(str.TrimEnd()); // 输出 "   Hello World"

Contains(string value):判断字符串是否包含指定的子字符串

csharp 复制代码
string str = "Hello World"; 
Console.WriteLine(str.Contains("World")); // 输出 True

StartsWith(string value) 和 EndsWith(string value):判断字符串是否以指定的子字符串开始或结束

csharp 复制代码
string str = "Hello World";  
Console.WriteLine(str.StartsWith("Hello")); // 输出 True  
Console.WriteLine(str.EndsWith("World")); // 输出 True

PadLeft(int totalWidth) 和 PadRight(int totalWidth):在字符串的左侧或右侧填充空格,直到达到指定的总宽度

csharp 复制代码
string str = "123";  
Console.WriteLine(str.PadLeft(5)); // 输出 "   123"(左侧填充3个空格)  
Console.WriteLine(str.PadRight(5, '*')); // 输出 "123**"(右侧填充2个'*')

Join(string separator, params string\[\] values):将多个字符串连接成一个字符串,并使用指定的分隔符分隔它们

csharp 复制代码
string[] words = { "Hello", "World", "C#" };  
string sentence = string.Join(", ", words);  
Console.WriteLine(sentence); // 输出 "Hello, World, C#"

Format(string format, params object\[\] args):格式化字符串,将指定的参数插入到格式字符串中

csharp 复制代码
string name = "John";  
int age = 30;  
string formattedString = string.Format("Name: {0}, Age: {1}", name, age);  
Console.WriteLine(formattedString); // 输出 "Name: John, Age: 30"

IsNullOrEmpty(string value):判断字符串是否为空或null

csharp 复制代码
string str = null; 
Console.WriteLine(string.IsNullOrEmpty(str)); // 输出 True

IsNullOrWhiteSpace(string value):判断字符串是否为空、null或仅包含空白字符

csharp 复制代码
string str = " "; 
Console.WriteLine(string.IsNullOrWhiteSpace(str)); // 输出 True

Concat(params string\[\] values):连接多个字符串并返回一个新的字符串

csharp 复制代码
string result = string.Concat("Hello", " ", "World"); Console.WriteLine(result); // 输出 "Hello World"

CopyTo(int sourceIndex, char\[\] destination, int destinationIndex, int count):将字符串中的字符复制到指定的字符数组中

csharp 复制代码
char[] charArray = new char[5];  
string str = "Hello";  
str.CopyTo(0, charArray, 0, 5);  
Console.WriteLine(new string(charArray)); // 输出 "Hello"(注意:超出字符串长度的部分不会被复制,保持默认值)

IndexOfAny(char\[\] anyOf) 和 LastIndexOfAny(char\[\] anyOf):查找字符数组中字符在字符串中第一次或最后一次出现的位置

csharp 复制代码
string str = "Hello World";  
char[] chars = { 'o', 'W' };  
Console.WriteLine(str.IndexOfAny(chars)); // 输出 4('o'的位置)  
Console.WriteLine(str.LastIndexOfAny(chars)); // 输出 6('W'的位置)

PadLeft(int totalWidth, char paddingChar) 和 PadRight(int totalWidth, char paddingChar):在字符串的左侧或右侧填充指定的字符,直到达到指定的总宽度

csharp 复制代码
string str = "123";  
Console.WriteLine(str.PadLeft(5, '*')); // 输出 "**123"(左侧填充2个'*')  
Console.WriteLine(str.PadRight(5, '*')); // 输出 "123**"(右侧填充2个'*')

Remove(int startIndex):从指定索引开始移除字符串的剩余部分

csharp 复制代码
string str = "Hello World"; 
Console.WriteLine(str.Remove(6)); // 输出 "Hello "

Insert(int startIndex, string value):在指定索引处插入一个字符串

csharp 复制代码
string str = "Hello"; 
Console.WriteLine(str.Insert(5, " World")); // 输出 "Hello World"

字符串插值(String Interpolation)(C# 6.0及更高版本):使用$符号和大括号{}来嵌入变量或表达式,从而创建格式化的字符串

csharp 复制代码
int age = 30;  
string name = "Alice";  
string message = $"My name is {name} and I am {age} years old.";  
Console.WriteLine(message); // 输出 "My name is Alice and I am 30 years old."

相关推荐
长友cy2 分钟前
Qt官方示例Application源码阅读
开发语言·qt
程序员良辰9 分钟前
服务器 JDK 环境变量配置:一键安装和手动配置有什么区别?
开发语言·python
奈斯先生Vector16 分钟前
本地图片识别怎么接入多模态 AI?用 Python API 理解 GPT-4o Vision 的真实工作流
开发语言·人工智能·windows·python·网络协议·http·aigc
OPEN-F20 分钟前
C++17新特性精讲:结构化绑定、if constexpr与实用类型
开发语言·c++
OPEN-F23 分钟前
C++并发编程:线程与互斥锁
开发语言·c++
俊昭喜喜里25 分钟前
C#中的decimal
开发语言·c#
catchadmin36 分钟前
免费可商用 PHP 管理后台 CatchAdmin V5.4.0 发布,新增短信服务能力
开发语言·php
小白学大数据1 小时前
API 调用错误处理实战:分层定位、有纪律地重试与可观测性设计
开发语言·网络·人工智能
萧瑟余晖1 小时前
Java深入解析篇十三之Java日志API(JUL)详解
java·开发语言
luj_17682 小时前
毒素驱动的生物自毁机制探析
服务器·c语言·开发语言·经验分享·算法