C#-从入门到精通-第5章 字符与字符串(2)

【截取字符串】
使用Substring方法。

string strA = "用一生下载你!";
string strB = strA.Substring(1, 4);               
Console.WriteLine(strB);           //输出 一生下载
string strC = strA.Substring(1, strA.IndexOf("载"));
Console.WriteLine(strC);   //输出一生下载
Console.ReadLine();  

【分割字符串】
使用Split方法。

//分割的符号有多种的情况
string strA = "1441127216@qq.com@com#com"; //要分割的字符串
char[] ch = { '@', '.', '#'};  //声明 分割字符的数组
string[] strB = strA.Split(ch);//分割字符串
for(int i=0;i<strB.Length;i++)
{
        Console.WriteLine(strB[i]);
}
Console.ReadLine();
//分割的符号只有一种的情况
string strA = "1441127216@qq.com.com.com"; //定义字符串
string[] strB = strA.Split(new char[] { '.' }); //分割字符串
for(int i=0; i<strB.Length;i++)
{
         Console.WriteLine(strB[i]);
}
Console.ReadLine();
//分割的符号只有一种且要指定分割次数的情况
string strA = "1441127216@qq.com.com.com";
string[] strB = strA.Split(new char[] { '.' },2);   //2代表分割两次
for(int i=0; i<strB.Length;i++)
 {
         Console.WriteLine(strB[i]);
 }
 Console.ReadLine();

【插入字符串】
使用string类的Insert方法

string str1 = "Keep on never give up!"; //声明字符串
string str2 = str1.Insert(8, "going ");//在字符串str1 第8个位置前面插入going 
Console.WriteLine(str2);
Console.ReadLine();

【删除字符串】
使用string类的Remove方法。

string str1 = "Keep on never give up!"; //声明字符串
string str2 = str1.Remove(8);//将字符串第8位之后的全部删除
Console.WriteLine(str2);输出 Keep on
string str3 = str1.Remove(0, 14); //将字符串第0位开始的14个字符删除
Console.WriteLine(str3); //输出 give up!
Console.ReadLine(); 

【复制字符串】
1.使用Copy方法
Copy是静态方法,直接使用类名进行调用

string str1 = "Do one thing at a time,and do well!"; //声明字符串
string str2 = string.Copy(str1); //使用string类名调用copy方法,将str1内容全部复制到str2
Console.WriteLine(str2);
Console.ReadLine();

2.CopyTo方法
该方法是void类型,说明其没有返回值

string str1 = "Do one thing at a time,and do well!";//声明字符串
char[] str2 = new char[4]; //声明字符数组,并初始化,长度为4个字符
str1.CopyTo(str1.IndexOf("time"), str2, 0, 4);//将time字符串,复制到str2中的第0位开始的4个字符
Console.WriteLine(str2);
Console.ReadLine();

【替换字符串】
使用replace方法。

string str1 = "馒头一文一个";  //声明字符串
string str2 = str1.Replace("一","壹"); //将单个字符串  一替换成壹
Console.WriteLine(str2);
string str3 = str2.Replace("馒头", "馍馍"); //将子字符串 馒头 替换成 馍馍
Console.WriteLine(str3);
Console.ReadLine(); 

/仅作为本人学习笔记/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一个喜欢弹吉他的程序猿

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

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

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

打赏作者

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

抵扣说明:

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

余额充值