C# 字符串操作

string到byte[]转换:

Encoding myEncoding = Encoding.GetEncoding("utf-8");
1.从string到byte[]
string sData = “字符串”;
byte[] myByte = myEncoding.GetBytes(sData);

2.从byte[]到string
byte[] myByte = new byte[]{};
string sData = myEncoding.GetString(byte[] myByte);

字符串比较:
int result=String.Compare(string,string,boolean)
其中boolean设为true,表示不区分大小写的比较。
返回值为0表示:  相等      strA 与 strB 在排序顺序中出现的位置相同。
返回值为-1表示: 小于      strA 在排序顺序中位于 strB 之前
返回值为1表示:  大于      strA 在排序顺序中位于 strB 之后

字符串分割三种常用方式:

1.使用Substring

2.使用Split

3.使用正则表达式Regex.Split

Substring:

Split:

Regex.Split:

多个字符来分隔:

string str="aabccdee"; 
string[] sArray=str.Split(new char[2] {'b','d'}); //aaccee

用字符串分隔:
 

using System.Text.RegularExpressions;
string str="aabdccee";
string[] sArray=Regex.Split(str,"bd",RegexOptions.IgnoreCase);//aaccee


以换行(\r\n)拆分字符串:

字符串数组形式:
string[] striparr = strip.Split(new string[] { "\r\n" }, StringSplitOptions.None);
striparr = striparr.Where(s => !string.IsNullOrEmpty(s)).ToArray();

List<sting>形式:
List<string> striparr = strip.Split(new string[] { "\r\n" }, StringSplitOptions.None).ToList();
striparr = striparr.Where(s => !string.IsNullOrEmpty(s)).ToList();

获取括号内字符串:

string str = "aaa(12)bbb[34]ccc{56}ddd";
string str1 = Regex.Replace(str, @"(.*\()(.*)(\).*)", "$2"); //小括号()内值:12
Regex rgx = new Regex(@"(?i)(?<=\[)(.*)(?=\])");
string str2 = rgx.Match(str).Value;//中括号[]内值:34  
//大括号{}内值:56
string str3 = Regex.Match(str, @"\{(.*)\}", RegexOptions.Singleline).Groups[1].Value;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无熵~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值