c#中字符串的方法练习
1、将字符串字符反输出
string s = "123456";
char[] chs = s.ToCharArray();//将字符串转换成字符数组
for (int i = 0; i < chs.Length / 2; i++)
{
char tmp = chs[i];//交换第一个与最后一个的值
chs[i] = chs[chs.Length - 1 - i];
chs[chs.Length - 1 - i] = tmp;
}
s = "";
for (int j = 0; j < chs.Length; j++)
{
s += chs[j];//通过遍历数组,字符数组转换成字符串
}
Console.WriteLine(s);
Console.ReadKey();
结果如图

2、 将“hello you world”反向输出“world you hello”
string s = "hello you world";
string[] str = s.Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries);//此时得到的字符串为str[0]=hello,str[1]=you.str[2]=world
for (int i = 0; i < str.Length/2; i++)//将str数组中的元素交换位置
{
string tmp = str[i];
str[i] = str[str.Length - 1 - i];
str[str.Length - 1 - i] = tmp;
}
s = "";
for (int i = 0; i < str.Length; i++)
{
s += str[i]+"";
}
Console.WriteLine(s);
Console.ReadKey();

3、找用户名和域名
string s = "1508602377@qq.com";
int index = s.IndexOf('@');//先使用inedexof得到'@'的位置,然后使用substring函数截取长度
string name = s.Substring(0,index);//sSubstring是从索引0开始,长度为10所以不包括'@'
string yuMing = s.Substring(index + 1);
Console.WriteLine(name);
Console.WriteLine(yuMing);
Console.ReadKey();

4、找出字符串中所有e所在的位置
string s = "aghdeyeeeeeyeueyeieiueiueehjehjeejj";
int index = s.IndexOf('e');//先判断出第一次出现e的地方
Console.WriteLine("第1次出现'e'的位置是{0}",index);
int count = 1;
while (index != -1)//当找不到e的时候,indexof返回的是-1
{
count++;
index = s.IndexOf('e', index + 1);//每次从e出现的下一个位置开始查找.所以+1
if (index == -1)
{
break;
}
Console.WriteLine("第{0}次出现e的地方是{1}",count,index);
}
Console.ReadKey();

5、让用户输入一句话判断有没有邪恶两个字,有的话用**替换
string s = "老赵是个邪恶的人";
if (s.Contains("邪恶"))//使用contains检查时候包含指定的字符串,返回bool类项
{
s = s.Replace("邪恶", "**");//replace是将指定的字符串替代成另一个字符串
Console.WriteLine(s);
}
else
{
Console.WriteLine("不存在邪恶");
}
Console.ReadKey();

6、把{“诸葛亮”,“鸟叔”,“卡哇伊”},变成诸葛亮|鸟叔|卡哇伊,然后再将|去除
string[] s = { "诸葛亮", "鸟叔", "卡哇伊" };
string str = string.Join("|",s);
Console.WriteLine(str);
string str1 = "";
s = str.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < s.Length; i++)
{
str1 += s[i] + " ";
}
Console.WriteLine(str1);
Console.ReadKey();
