day 15 C# 字符串的方法补充

day 15 C#打卡

1.创建一个计时器记录程序运行时间

using System;
using System.Diagnostics;
using System.Text;

namespace ConsoleApp14
{
    class Program
    {
        static void Main(string[] args)
        {
            //alt+shift+F10 引用命名空间
            StringBuilder sb = new StringBuilder();

            Stopwatch sw = new Stopwatch();            
            //创建了一个计时器,用来记录程序运行时间

            sw.Start();//开始计时

            for(int i=0;i<100000;i++)
            {
                sb.Append(i);//Append就是+=的意思
            }
            sw.Stop();//结束计时

            //Console.WriteLine(sb.ToString());
            Console.WriteLine(sw.Elapsed);
        }
    }
}

字符串每创建一个值就会在堆里开辟一个空间,字符串拥有不可变性,即string s1=“123”;string s1=“234”;123仍在堆里面。

2.Split()的补充

using System;


namespace ConsoleApp14
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "a b   dfg_  +=  ,,, fff";

            char[] vs = { ' ', '_', '+', '=', ',' };//字符数组存放符号

            string[] str = s.Split(vs, StringSplitOptions.RemoveEmptyEntries);
            //分割字符串,但是空间中仍会留下空白字符串,于是用RemoveEmptyEntries移除掉空白

            for (int i = 0; i < str.Length; i++)
                Console.Write(str[i]);
            Console.ReadKey();
        }
    }
}

在这里插入图片描述

using System;


namespace ConsoleApp14
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入你的出生年月(例如2008-08-08):");
            string s = Console.ReadLine();
            string[] date = s.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
            Console.WriteLine("{0}年{1}月{2}日", date[0], date[1], date[2]);
            Console.ReadKey();
        }
    }
}

在这里插入图片描述
3.IndexOf()与Substring()

using System;


namespace ConsoleApp14
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"C:\a\苍b\苍c\d\e\f\g\v\苍老师苍.wav";//@用来消除斜杠的作用
            int index = path.LastIndexOf("\\");// 前面一个斜杠是转义字符
            path = path.Substring(index + 1);//因为\占一个位置所以加一跳转到下一个位置
            Console.WriteLine(path);
        }
    }
}

在这里插入图片描述
IndexOf索引位置包括当前位置,
例如str.IndexOf(‘天’,2)返回的还是2,
Substring同样也包括当前位置。

字符串还有其他方法,如
string.IsNullOrEmpty(字符串名) 判断字符串是否为空
字符串名.Contains(“字符串”) 判断字符串中是否包含某个字符串

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值