字符串的练习
1.接受用户输入的字符串,将其中的字符以输入相反的顺序输出(例如,"abc'--"cab'')
解法1:用for循环的倒叙,但这样并有改变字符串的值
string str = "werthueyihziiou";
//倒叙循环
for (int i = str.Length - 1; i >= 0; i--)
{
Console.Write(str[i]);
}
解法2:元素反转
第一个和最后一个交换,第二个和倒数第二个交换等等,总结规律为 交换次数为.Length/2
交换数为:i--.Length-1-i
代码如下:
string str = "werthueyihziiou";
char[] chs = str.ToCharArray();
for (int i = 0; i < str.Length / 2; i++)
{
char temp = chs[i];
chs[i] = chs[str.Length - 1 - i];
chs[str.Length - 1 - i] = temp;
}
str=new string(chs);
Console.WriteLine(str);
2.将一个字符串 hello c sharp 变为sharp c hello
string str = "hello c sharp";
string[] a = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < a.Length / 2; i++)
{
string temp = a[i];
a[i] = a[a.Length - 1 - i];
a[a.Length - 1 - i] = temp;
}
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
str=string.Join(' ', a);
3.从E-mail中提取出用户名和域名:sdf@163.com
string email = "sdf@163.com";
string usersName = email.Substring(0, email.IndexOf('@'));
string yuNamw = email.Substring(email.IndexOf('@') + 1);
Console.WriteLine("用户名为:{0},域名为{1}", usersName, yuNamw);
4.文本文件中存储了多个文章标题,作者,标题和作者之间用若干空格(数量不定)隔开,每行一个。标题有长有短,输出到控制台的时候,标题长度最大为10,若超过10,则截取长度8的字串并且最后添加“……”,加一个竖线后输出作者名字。
题目分析:
标题 作者
古代帝王兴衰 XXX
坏蛋是怎样练成的炼成的 345六道
C#基础之循环结构while,dowhile 小侯
要把以上内容打印到控制台,若长度超过10,例如:坏蛋是怎样练成的……
string path = @"C:\Users\86184\Desktop\t.txt";
string[] a=File.ReadAllLines(path);
for (int i = 0; i < a.Length; i++)
{
string[] s=a[i].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine((s[0].Length>10?s[0].Substring(0,8)+"......":s[0]) + "|" + s[1]);
}
5.让用户输入一句话,找出所有e的位置
解法一
string str = "abcdefgabcdefgabcdefg";
int index = str.IndexOf('e');
Console.WriteLine("第1次出现e的位置是{0}", index);
//循环体:从上一次出现e的位置加1的位置找下一次e出现的位置
//循环条件:index!=-1;
int count = 1;//用来记录e出现的次数
while (index != -1)
{
count++;
index = str.IndexOf('e', index + 1);
if (index == -1)
{
break;
}
Console.WriteLine("第{0}次出现e的位置是{1}", count, index);
}
解法二
int count = 0;
string str = "abcdefgabcdefgabcdefg";
for (int i = 0; i < str.Length; i++)
{
count++;
if (str[i] == 'e')
{
Console.WriteLine("第{0}次出现e的位置是{1}", count, i);
}
}
6.用户输入一句话,判断这句话中有没有邪恶,如果有邪恶就替换成这种形式输出,如:老牛很**
string str = "老牛很邪恶";
if (str.Contains("邪恶"))
{
str=str.Replace("邪恶", "**");
}
Console.WriteLine(str);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)