c#常用字符串方法

1、字符串比较:

3种方法 ==/CompareTo/Equals

Button btn = (Button)sender;

  if (btn.Text=="比较1")

  {

        MessageBox.Show("你点击了button1");

    }

    else if (btn.Text.CompareTo("比较2")==0)

    {

        MessageBox.Show("你点击了button2");

    }

    else if (btn.Text.Equals("比较3"))

    {

        MessageBox.Show("你点击了button3");

}

2、字符串格式化

string name = "chenzhigang";

int age = 30;

string sText = String.Format("name={0},age={1}",name,age);

MessageBox.Show(sText);

3、时间日期格式化
DateTime dt = DateTime.Now;

//格式化结果 2020-05-18

String text = String.Format("{0:d}",dt);

//格式化结果 2020-05-1 8 20:35:30

String sText = String.Format("{0:G}",dt);

MessageBox.Show(sText);

4、截取字符串(与Delphi的Copy类似)

String s1 = "HelloWorld";

//截取字符串,字符串索引从0开始

String s2 = s1.Substring(1,4);

MessageBox.Show(s2);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               5、字符串切割

String s1 = "20,30,40";

char[] a = new char[1];

a[0] = ',';

String[] b = null ;

b = s1.Split(a);

 

6、插入字符串

String s1 = "HelloWold";

String s2 = s1.Insert(1,"nihao");

MessageBox.Show(s2); 

 

7、再字符串左侧或右侧填充字符

String s1 = "HelloWold";

String s2 = s1.PadLeft(13,'H');

String s3 = s1.PadRight(13, 'H');

MessageBox.Show(s2);

 

8、删除字符串

String s1 = "HelloWold";

 //从索引3开始,删除全部字符

String s2 = s1.Remove(3);

 //删除索引是3,4,5的字符

 String s3 = s1.Remove(3,3);            

 MessageBox.Show(s2);

 

9、字符串替换

String s1 = "HelloHeWold";

String s2 = s1.Replace("He","SHE");            

MessageBox.Show(s2);  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值