C# 字符串相关方法的介绍

本文通过一个C#程序实例展示了多种字符串操作方法的应用,包括获取长度、截取、转换大小写、替换字符、检查是否为空、查找子串起始位置、插入与删除字符等常见操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

namespace 字符串方法练习
{
    class Program
    {
        static void Main(string[] args)
        {
            string MyStr = " Hello World! ";
            //长度
            int leng = MyStr.Length;
            Console.WriteLine(leng);

            //SubStrings 截取字符串
            string  s = MyStr.Substring(0, MyStr.Length - 5);
            Console.WriteLine(s);
            char[] ch = MyStr.ToCharArray();
            Console.WriteLine(ch[2]);

            //转换为大写、小写
            Console.WriteLine(MyStr.ToUpper());
            Console.WriteLine(MyStr.ToLower());

            //替换
            Console.WriteLine(MyStr.Replace("H","W"));

            //判断是否空值 
            bool bl = string.IsNullOrEmpty(MyStr);
            Console.WriteLine(bl);

            //开头
            bool bol = MyStr.StartsWith(" He");
            Console.WriteLine(bol);

            //第一个出现的索引  
            int n1 = MyStr.IndexOf("o");
            Console.WriteLine(n1);

            //插入
            string str_new1= MyStr.Insert(2, "fff");
            Console.WriteLine(str_new1);

            //移除
            string str_new2 = MyStr.Remove(3, 2);
            Console.WriteLine(str_new2);

            //比较
            string c1 = "abcdefg";
            string c2 = "abcdefg";
            int c12 = string.Compare(c1, c2);
            Console.WriteLine(c12);

            Console.ReadKey();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值