C#学习:字符串综合练习

传智播客.Net培训—C#编程基础(杨中科)视频题目练习

练习1、接收用户输入的字符串,将其中的字符以与输入相反的顺序输出。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 字符串综合练习
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = Console.ReadLine();
            for (int i = s.Length - 1; i >= 0; i--)
            {
                Console.Write(s[i]);
            }
            Console.ReadKey();
        }

    }
}

执行结果:

 练习2、文本文件中存储多个文章标题、作者,标题和作者之间用若干个空格(数量不定)隔开,每行一个,标题有长有短,输出到控制台的时候最多标题长度为10,若超过10则只截取前半部分并在最后添加“...”,加上竖线后输出作者名字。

文本文件如图,存储在d:/,名称为2.txt

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 字符串综合练习文件标题截断
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] lines = System.IO.File.ReadAllLines(@"d:\2.txt", Encoding.Default); //按行将文件内容取出
            foreach (string line in lines)   //遍历每行内容
            {
                string[] strs = line.Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries);  //移除空格
                string title = strs[0];  //得到文章标题
                string author = strs[1];  //得到作者名
               
                string title1=title.Substring(0, Math.Min(10,title.Length));  //标题长度或为10或为实际长度(取小的那个值)
                if (title.Length > 10)  //如果原标题长度大于10,加入省略号
                {
                    title1 = title1 + "...";
                }
                Console.WriteLine("{0}|{1}", title1, author);
                
            }
            Console.ReadKey();
        }
    }
}

执行结果:


 练习3、从ini格式的文件中(每行是“键=值”格式)中读取配置项的值,编写一个函数来读这些文件;读取指定文件的某个配置项的值。

string GetConfigValue(string filename, string itemName)

 文本文件如图,存储在d:/,名称为3.txt

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {  
            string value = GetConfigValue(@"d:\3.txt", "端口");
            Console.WriteLine(value);
            Console.ReadKey();
        }
        static string GetConfigValue(string filename, string itemName)
        {
            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 == itemName)
                {
                    return value;
                }
               
            }
            return "错误";

        }

    }
}

执行结果:

查询端口号:

查询IP地址:

文本文件中没有所查询的键时:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值