题一://翻转字符串s
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
string s = "asdfghjk"; for (int i = s.Length-1; i >= 0;i-- )//遍历的方式倒序输出 { Console.Write(s[i]); } Console.ReadKey(); } 方法二: string s = "asdfghjk"; char[] chs= s.ToCharArray(); for (int i = 0; i < s.Length/2; i++)//首尾交换 { char temp = chs[i]; chs[i] = chs[s.Length - i - 1]; chs[s.Length - i - 1] = temp; } //s=chs.ToString();//错误 s = new string(chs);//字符数组转字符串 不能直接这样转s=chs.ToString() Console.Write(s); Console.ReadKey(); |
注意:
一:字符串数组不能直接转字符串需要遍历输出后在tostring
字符数组可以直接用 s = new string(chs); 但不能直接这样转s=chs.ToString()
二:翻转一个字符数组最少循环 (数组长度/2)次
题二: //倒序输出字符串I like china
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
string s = "I like china"; string[] chs=s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i <chs.Length/2; i++) { string Temp = chs[i]; chs[i] = chs[chs.Length - i - 1]; chs[chs.Length - i - 1] = Temp; } for (int i = 0; i < chs.Length; i++)//for循环遍历输出 { Console.Write(chs[i]); Console.Write(" "); } 解法二:string.join string s = "I like china"; string[] chs=s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i <chs.Length/2; i++) { string Temp = chs[i]; chs[i] = chs[chs.Length - i - 1]; chs[chs.Length - i - 1] = Temp; } s=string.Join(" ", chs);//返回一个字符串重新赋值给s Console.Write(s); Console.ReadKey(); |
题三: //找到字符串中含有f的位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
string s = "sdfdfrrttrtrfsdvdffnfgnhlo"; int index=s.IndexOf("f"); int count = 0; while (index != -1) { count++; index=s.IndexOf("f", index + 1); if (index == -1) { break; } Console.WriteLine("第{0}次出现f的位置为{1}",count,index); } Console.ReadKey(); |