C#字符串及其常用方法

1. string.Format

string.Format() 方法允许我们创建格式化的字符串,其中包含一个或多个占位符,可以用实际值来替换这些占位符。

//基础语法
string.Format("格式字符串", 参数1, 参数2, ...)
    
//应用
string str = "帅哥";
Console.WriteLine(string.Format("我是{0}",str));
//输出结果为:我是帅哥

2. string.IsNullOrEmpty

string.IsNullOrEmpty() 是 C# 中检查字符串是否为 null 或长度为 0 的常用方法。如果是0或空,返回true,反之返回false。

string username = null;

if (string.IsNullOrEmpty(username))
{
    Console.WriteLine("0或空");
}
else
{
    Console.WriteLine("不为0或空");
}

3. Equals

Equals() 方法用于比较两个字符串是否相等。

两个字符串相同返回true,反之为false

注意:equals进行比较时区分大小写。

string str1 = "Hello";
string str2 = "hello";
bool result = str1.Equals(str2); 
// result 为 false

string str1 = "Hello";
string str2 = "Hello";
bool result1 = str1.Equals(str2); 
// result1 为 true

4. Contains

Contains() 方法用于检查一个字符串是否包含另一个字符串。

包含返回true,反之返回false。

//基本语法
string1.Contains(string2);

//基本用法
string str3 = "hello,world";
if (str3.Contains("hello"))
{
    Console.WriteLine("Yes");
}
else
{
    Console.WriteLine("No");
}
//输出为Yes

也可以判断是否包含某个字符:

string str3 = "hello,world";
if (str3.Contains(","))
{
    Console.WriteLine("Yes");
}
else
{
    Console.WriteLine("No");
}
//输出为Yes

5. Length

获取字符串的长度。

string str = "hello,world";
Console.WriteLine(str.Length);
//输出结果为11

6. Substring

Substring() 方法用于从一个字符串中提取一部分字符串,它有两种常见的使用方式:

  1. 从指定的索引位置开始提取:
string str4 = "hello,world,你好";
Console.WriteLine(str4.Substring(6));
//输出为 world,你好
  1. 从指定的索引位置开始,提取指定长度的子字符串:
string str4 = "hello,world,你好";
Console.WriteLine(str4.Substring(6,5));
//输出为 world

注意:字符串本质为字符数组,所以下标应从0开始计算。

7. IndexOf和LastIndexOf

IndexOf()用于查找指定子字符串在当前字符串中首次出现的索引位置。找不到则返回-1.

string text = "hello,world,你好,世界";
int index1 = text.IndexOf("world"); 
Console.WriteLine(index1); //输出6
int index2 = text.IndexOf("hello6");
Console.WriteLine(index2); //输出-1

LastIndexOf()用于查找指定子字符串在当前字符串中最后一次出现的索引位置。找不到也返回-1。

string text = "hello,world,world,你好,世界";
int index1 = text.LastIndexOf("world"); 
Console.WriteLine(index1);//输出12
int index2 = text.LastIndexOf("hello6");
Console.WriteLine(index2);//输出-1

8. Remove

Remove() 方法用于从字符串中移除一部分字符,有两种常见的使用方式:

  1. 从指定的索引位置开始移除
string str = "hello,world,你好,世界";
Console.WriteLine(str.Remove(5));
//输出结果为:hello
  1. 从指定的索引位置开始移除指定长度的字符
string str = "hello,world,你好,世界";
Console.WriteLine(str.Remove(6,6));
//输出结果为:hello,你好,世界

注意索引位置是从0开始计算的。

9. Reverse

反转字符串。

string str5 = "我是帅帅";
Console.WriteLine(str5.Reverse().ToArray());
//输出结果为:帅帅是我

10. Replace

用指定的新字符替换所有出现的指定的旧字符。

string str = "hello,world,world";
Console.WriteLine(str.Replace("world", "hello"));
//输出结果为:hello,hello,hello

也可以用空字符串替换空格,实现数据清洗的效果

string str = "he  llo,w or ld,w or ld";
Console.WriteLine(str.Replace(" ", ""));
//输出为:hello,world,world

11. Trim

Trim() 方法用于从字符串的开头和结尾移除空白字符。

string str6 = "   aaa   ";
Console.WriteLine("-" + str6.Trim()+"-");

若要去除字符串内的空格,可以用replace。

12. string.Concat

Concat() 方法用于将一个或多个字符串连接成一个新的字符串。有多种重载形式,可以接受不同类型的参数。

连接两个字符串并返回一个新的字符串。

string str = "hello";
string str1 = "world";
string str2 = string.Concat(str, str1);
Console.WriteLine(str2);
//输出为:helloworld

也可以连接一个字符串集合并返回一个新的字符串。

string[] names = { "李白", "关于", "张飞", "刘备" };
string nameall = string.Concat(names);
Console.WriteLine(nameall);
//输出为:李白关于张飞刘备

string.Join

13. string.Join

方法用于将一个字符串集合连接成一个新的字符串,中间用指定的分隔符分隔。

string[] names = { "李白", "关于", "张飞", "刘备" };
Console.WriteLine(string.Join(",", names));
//输出为:李白,关于,张飞,刘备

14. Split

Split() 方法用于将一个字符串按指定的分隔符拆分成一个字符串数组。

string name = "小明,小红,小兰,小黑";
string[] names = name.Split(',');
foreach(string n in names)
{
    Console.WriteLine(n);
}
//输出为:
// 小明
// 小红
// 小兰
// 小黑

15. 实现身份证的解析;

首先了解身份证号码的组成部分

身份证号码共18位,由17位本体码和1位校验码组成。其中:

  1. 前6位是地址码,表示登记户口时所在地的行政区划代码。
  2. 7到14位是出生年月日,采用YYYYMMDD格式。
  3. 15到17位是顺序码,表示在同一地址码所标识的区域范围内,对同年、同月、同日出生的人编订的顺序号。
  4. 第18位是校验码,用于验证身份证号码的合法性

然后用Substring和即可对不同位置进行分割获取

string id = "412833200411262675";

string num1 = id.Substring(0,6);
string num2 = id.Substring(6, 8);
string num3 = id.Substring(14, 3);
string num4 = id.Substring(17,1);

Console.WriteLine($"地址码:  {num1}");
Console.WriteLine($"出生日期:{num2}");
Console.WriteLine($"顺序码:  {num3}");
Console.WriteLine($"校验码:  {num4}");

输出结果:

16. 遍历磁盘,列出目录和文件、统计文件个数,统计不同类型(后缀)的文件个数。

首先获取 D 盘的 DriveInfo 对象。这个对象提供了关于 D 盘的各种信息,如驱动器名称、文件系统类型、可用空间等。

初始化一个字典 fileTypeCount 用于统计不同类型文件的个数,以及一个整型变量 totalFileCount 用于记录总的文件数量。

调用 AnalyzeDirectory() 方法,传入 D 盘的根目录路径、fileTypeCount 字典和 totalFileCount 的引用。这个方法将递归地遍历 D 盘的目录和文件。

在AnalyzeDirectory()函数中,

使用Directory.GetDirectories(path) 获取当前目录下的所有子目录,并递归地调用自己来分析每个子目录。在输出目录名称之后,递归调用。

最后,输出统计结果,包括总文件数和各种文件类型的文件数量。

    public void AnalyzeDisk()
    {
        // 获取D盘的DriveInfo对象
        DriveInfo dDrive = new DriveInfo("D");

        // 用于统计不同类型文件的个数
        Dictionary<string, int> fileTypeCount = new Dictionary<string, int>();

        int totalFileCount = 0;

        // 分析D盘
        AnalyzeDirectory(dDrive.RootDirectory.FullName, fileTypeCount, ref totalFileCount);

        // 输出统计结果
        Console.WriteLine($"Total files: {totalFileCount}");
        Console.WriteLine("File type count:");
        foreach (var kvp in fileTypeCount)
        {
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
        }
    }

    private void AnalyzeDirectory(string path, Dictionary<string, int> fileTypeCount, ref int totalFileCount)
    {
        try
        {
            // 列出目录和文件
            foreach (string directory in Directory.GetDirectories(path))
            {
                Console.WriteLine($"Directory: {directory}");
                AnalyzeDirectory(directory, fileTypeCount, ref totalFileCount);
            }

            foreach (string file in Directory.GetFiles(path))
            {
                Console.WriteLine($"File: {file}");
                totalFileCount++;

                // 统计文件类型
                string extension = Path.GetExtension(file).ToLower();
                if (fileTypeCount.ContainsKey(extension))
                {
                    fileTypeCount[extension]++;
                }
                else
                {
                    fileTypeCount[extension] = 1;
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error analyzing {path}: {ex.Message}");
        }
    }
} 

temp t = new temp();
t.AnalyzeDisk();

运行结果:

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值