C#自学笔记

it2026-08-19  5

C#自学笔记_009_Real(字符串函数练习)

using System; using System.Collections.Generic; using System.IO; //该类中含有用于对txt文件进行操作的函数 using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Http.Headers; namespace Csharp009stringtraining { class Program { static void Main(string[] args) { //字符串练习:文本文件中存储了多个文章标题,作者 //标题和作者之间用若干空格(数量不定)隔开,每行一个 //标题有的长有的短,输出到控制台的时候最多标题长度10 //如果超过10,则截取长度8的字符串并且最后添加“...”, //加一个竖线后输出作者的名字。 string path = @"E:\C#learningfile\Csharp009stringtraining\trainingfile.txt"; string[] contents = File.ReadAllLines(path); for (int i = 0; i < contents.Length; i++) { string[] strNew = contents[i].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); Console.WriteLine((strNew[0].Length > 8 ? strNew[0].Substring(0, 8) + "......" : strNew[0]) + "|" + strNew[1]); } //练习2:接收用户输入的字符串,将其字符串的字符以与输入相反的顺序输出 string str = "abcdefg"; char[] chs = str.ToCharArray(); for (int i = 0; i < chs.Length / 2; i++) { char temp; temp = chs[i]; chs[i] = chs[chs.Length - 1 - i]; chs[chs.Length - 1 - i] = temp; } str = new string(chs); Console.WriteLine(str); //练习3:用户输入一句话:“Hello c sharp.”,将输入的话按照单词倒序输出 string str = "Hello c sharp"; string[] strNew = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < strNew.Length / 2; i++) { string temp; temp = strNew[i]; strNew[i] = strNew[strNew.Length - 1 - i]; strNew[strNew.Length - 1 - i] = temp; } str = string.Join(" ", strNew); Console.WriteLine(str); //l练习4:从Email中提取出用户的用户名和域名 string email = "abcedf@outlook.com"; //方法一:利用索引函数 int index = email.IndexOf('@'); string userName = email.Substring(0, index); string yuMing = email.Substring(index + 1); Console.WriteLine(userName); Console.WriteLine(yuMing); //方法二:利用分割函数进行输出 string[] strNew = email.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries); Console.WriteLine(strNew[0]); Console.WriteLine(strNew[1]); //练习5:让用户输入一句话,找出话总所有e的位置 string str = "abcdefhuigiyehodueenjekwe"; int index = str.IndexOf('e'); Console.WriteLine("第1次出现e的位置是{0}", index); int count = 1; while (index != -1) { count++; index = str.IndexOf('e', index + 1); if (index == -1) { break; } Console.WriteLine("第{0}次出现e的位置是{1}", count, index); } Console.ReadKey(); } } }

txt文件

最新回复(0)