C#学习笔记:string字符串的操作,包括查找字符串增删查改

参考书目:C#6.0学习笔记——从第一行C#代码到第一个项目设计(作者周家安)P158

学习目的:掌握string字符串的操作,包括查找字符串增删查改

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

namespace Example5_9
{
    class Program
    {
        static void Main(string[] args)
        {
            //-------整型数值的字符串转换为整形数值------
            string intStr = "210";
            int convInt = int.Parse(intStr);
            Console.WriteLine("将字符串{0}转化为int值:{1}", intStr, convInt);

            //-查找字符y 和a的索引,使用IndexOfAny找第一个匹配字符的索引-------
            //IndexOfAny找到任意一个字符,返回值就不是-1,
            string testStr = "check my app,check my app";
            char[] patts = { 'y', 'a' };    //查找的条件
            int index1 = testStr.IndexOfAny(patts);
            //返回第一个符合查找条件的字符索引
            Console.WriteLine("在{0}中查找{1}的索引:{2}", testStr, string.Join(
                ",", patts), index1);
            //Join作用是将数组的元素连接起来

            //-查找字符y 和a的索引,使用IndexOfAny找最后一个匹配字符的索引-------
            int index2 = testStr.LastIndexOfAny(patts);
            
            Console.WriteLine("在{0}中查找{1}的索引:{2}", testStr, string.Join(
                ",", patts), index2);

            //---------存在性查找---------
            //测试字符串"address"中是否包含字符串"re",测试大小写是否敏感
            string test_str1 = "address";
            string test_str2 = "addRess";
            bool result1 = test_str1.Contains("re");
            Console.WriteLine("字符串{0}中{1}re", test_str1, result1 ? "包含" : "不包含");

            bool result2 = test_str2.Contains("re");
            Console.WriteLine("字符串{0}中{1}re", test_str2, result2 ? "包含" : "不包含");
            //答案是大小写敏感

            //-------判断是否是字符串"address"中以ad开头-----
            bool result3 = test_str1.StartsWith("ad");
            Console.WriteLine("字符串{0}中{1}以ad开头", test_str1, result3 ? "是" : "不是");

            //----------字符串中添加新字符------
            string test_str4 = "大家好";
            string resultStr4 = test_str4.Insert(2, "晚上");
            Console.WriteLine("在字符串“{0}”中插入新字符“{1}”后的字符串为:“{2}”",
               test_str4, "晚上", resultStr4);

            testStr = "山重水复";
            // 删除字符
            string resultStr = testStr.Remove(1, 1).Remove(2, 1);
            Console.Write("去掉“{0}”中的“重”和“复”:{1}\n", testStr, resultStr);

            testStr = "bag";
            // 替换字符
            resultStr = testStr.Replace("b", "fl");
            Console.Write("将“{0}”中的“b”替换为“fl”:{1}\n", testStr, resultStr);

            testStr = "  name  ";
            // 去掉首尾的空格
            resultStr = testStr.Trim();
            Console.WriteLine("去掉“{0}”中首尾的空格:{1}", testStr, resultStr);


            Console.ReadKey();
        }
    }
}

运行结果如下:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值