(基础三)问题

课上练习1:接受用户输入的字符串,将其中的字符串与输入相反的顺序输出,如:"abc"→"cba"

            string str = Console.ReadLine();
char[] s = str.ToCharArray();
for (int i = s.Length - 1; i >= 0; i--) //注意是s.Length - 1
{
Console.Write(s[i]);
}

课上练习2:接受用户输入一句英文,将其中的单词以反序输出,如:"hello world and c#"→"c# and world hello"

            string str1 = Console.ReadLine();
string[] word = str1.Split(' ');
for (int i = word.Length - 1; i >= 0; i--)
{
Console.WriteLine(word[i]);
}

课上练习3:从email中提取用户名和域名,如:Abc@yahoo.com

            string user = Console.ReadLine();
int at = user.IndexOf('@');
string username = user.Substring(0, at);
Console.WriteLine("用户名:{0}",username);
string domin = user.Substring(at + 1);
Console.WriteLine("域名:{0}",domin);

课上练习4: 文本文件中存储了多个文章标题、作者,标题和作者之间用若干空格隔开,每行一个,标题有长有短,输出到控制台的时候最大长度20,如果超过20,则截取长度17的子串,并且最后添加……,加一个竖线后输出作者的名字

            string[] news = System.IO.File.ReadAllLines(@"D:\我的文件\测试1.txt", Encoding.Default);
foreach (string lines in news)
{
//string[] strs = lines.Split();
string[] strs=lines.Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries);
string title = strs[0];
string author = strs[1];
//title = title.Substring(0, Math.Min(17, title.Length));
//以上一句代码是计算17和标题长度之间的最小值,Math.Min
if (title.Length > 17)
{
title = title.Substring(0, 17);
title = title + "...";
}

Console.WriteLine("{0}|{1}", title, author);
}

课上练习5:从ini格式的文件中(每行是“键=值”格式)中读取出配置项的值

static void Main(string[] args)
{
string value = GetConfigValue(@"d:\我的文件\a.ini", "端口号");
Console.WriteLine(value);
Console.ReadKey();
}

static string GetConfigValue(string filename, string itemname)
{
//课上练习5:从ini格式的文件中(每行是“键=值”格式)中读取出配置项的值
string[] lines = System.IO.File.ReadAllLines(filename, Encoding.Default);
foreach (string line in lines)
{
string[] strs = line.Split('=');
string name = strs[0];
string value = strs[1];
if (name.Trim() == itemname)
{
return value.Trim();
}
}
return "错误"; //如果没有这一句,程序则存在没有返回值的情况
//Console.ReadKey();
}




 

posted @ 2012-01-27 19:25  王小萌  阅读(241)  评论(1编辑  收藏  举报