c# ---字符串的操作

本文详细介绍了C#中字符串的各种操作方法,包括截取、分割、插入、填充、删除、复制和替换等,帮助读者全面掌握字符串处理技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 截取字符串

  • pulic string Substring(int startIndex, int Length)
  • startIndex : 子字符串中的起始位置的索引
  • Length      :子字符串中字符数

  • 在用Substring截取字符串时,如果length参数的长度大于截取字符串的长度,将从起始位置的索引出截取之后索引的字符.

新版本的VS会直接报出异常

  1. 分割字符串

  • public string[] split(params char[] separator)

  1. 插入和填充字符串

  • 插入字符串:
  • public string Insert(int startIndex, string value)
  • startIndex : 用于指定所要插入的位置,  索引从0开始.
  • Value        : 指定所要插入的字符串

  • 填充字符串

  • String类提供了PadLeft/PadRight方法用于填充字符串,PadLeft在字符串左侧进行字符填充。而PadRight就是在字符串右侧进行字符填充。
  • public string PadLeft(int totalWidth,  char paddingChar)
  • public string PadRight(int totalWidth,  char paddingChar)
  • totalWidth : 指定填充后的字符串的长度
  • paddingChar : 指定所要填充的字符,  如果省略,则填充空格字符。

  1. 删除字符串

  • public String Remove(int startIndex)
  • public String Remove(int startIndex , int count)
  • startIndex : 用于指定开始删除的位置, 索引从0开始
  • count        : 指定删除的字符数量
  • *@*  参数count的值不能为0或是负数(startIndex参数耶不能为负数) , 如果为负数将会引发ArgumentOutOfRangeException异常;如果为0,则删除无意义,也就是没有进行删除

 

  1. 复制字符串

 

  • Copy方法
  • public static string Copy(string str)
  • str : 要复制的字符串
  • 返回值 : 与str具有相同值的字符串.
  • CopyTo
  • CopyTo方法的功能与Copy类似, 但是CopyTo可以将字符串的某一部分复制到另一个数组中
  • public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
  • sourceIndex 需要复制的字符的起始位置
  • destination  目标字符数组
  • destinationIndex  指定目标数组中的开始存放位置
  • count  指定要复制的字符个数
  1. 替换字符串

  • public string Replace(char OChar,char NChar)
  • public string Replace(string OValue,string NValue)s
  • OChar   代替换的字符
  • NChar   替换后的新字符
  • OValue  代替换的新字符串
  • NValue  替换后的新字符串

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值