C#学习笔记之字符串的使用1

字符串提供的各种方法

//1.Length:获得当前字符串中字符的个数

//2.ToUpper():将字符转换成大写形式

//3.ToLower():将字符串转换成小写形式

//4.Equals(lessinTwo,StringComparison.OrdinalIgnoreCase):比较字符串

//5.Split():分割字符串,返回字符串类型的数组、

//6.ToCharArray();将字符串转换成char数组

//7.new string(char[] chas):将char数组转换成字符串

代码示范

length的用法

#region 练习一length的用法

//随机输入你心中想的的一个名字,然后输出它的字符串长度,Length可以得到字符串的长度

Console.WriteLine(“随机输入你心中所想之人的名字”);

string name = Console.ReadLine();

Console.WriteLine(“你心中所想人的名字字符串长度是{0}”,name.Length);

#endregion

字符串转换大小写的应用ToUpper()和ToLower()

#region 练习二字符串转换大小写的应用ToUpper()和ToLower():

//两个学员输入各自最喜欢的课程名称,判断是否一致,如果一致,则输出你们喜欢的课程,如果不一致,则输出你们喜欢的不同课程。

Console.WriteLine(“请输入同学A喜欢的课程”);

string class1 = Console.ReadLine();

//class1 = class1.ToUpper();

//字母转换成大写形式

Console.WriteLine(“请输入同学B喜欢的课程”);

string class2 = Console.ReadLine();

//if (class1 ==class2)

if(class1.Equals(class2,StringComparison.OrdinalIgnoreCase))

//另一种方式直接比较大小的方式,忽略大小写

{

    ​Console.WriteLine("你们喜欢的课程一样");

}

else

{

   ​Console.WriteLine("你们喜欢的课程不一样");

 }

#endregion

字符串的分割-string[]Split(params char[] separator)

#region 练习三字符串的分割-string[]Split(params char[] separator)

//让用户输入日期格式2008-08-08,你输出的日期为2008年8月8日

Console.WriteLine(“输入日期如:2008-08-08”);

string m = Console.ReadLine();

char[] c = { ‘-’ };

string[]data= m.Split(c, StringSplitOptions.RemoveEmptyEntries);

//Split()分割字符串,返回字符串类型的数组。

Console.WriteLine("{0}年{1}月{2}号",data[0],data[1],data[2]);

#endregion

字符串的只读性

#region 字符串的只读性

string s = “abcdefg”;

//可以将string类型看做是char类型的一个只读数组,如果要将字符串中的a转换成b不能直接s[0]=‘b’;因为s是只读的字符串

char[] chas = s.ToCharArray();//首先应该先将字符串转换成char类

chas[0] = ‘b’;

Console.WriteLine(s[0]);

Console.WriteLine(s);

Console.WriteLine(chas[0]);//但是chas[0]与s[0]无关

s = new string(chas);

//开辟一个新空间存储改变后的字符串,即将数组转换成字符串

Console.WriteLine(s[0]);

Console.WriteLine(s);

#endregion

ToString的用法

#region ToString的用法

StringBuilder SB = new StringBuilder();

Stopwatch sw = new Stopwatch();

sw.Start();//开始计时

for (int i = 0; i < 100000; i++)

​{

​    ​SB.Append(i);//将i累加存放在SB中

​}

sw.Stop();//计时结束,记录上述for循环所用的时间Console.WriteLine(SB.ToString());

Console.WriteLine(sw.Elapsed);

#endregion

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值