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);