首页 > 编程语言 >C#字符串及其常用方法

C#字符串及其常用方法

时间:2024-07-05 20:30:05浏览次数:15  
标签:常用 Console string C# WriteLine 字符串 world hello

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();

运行结果:

标签:常用,Console,string,C#,WriteLine,字符串,world,hello
From: https://blog.csdn.net/m0_62801736/article/details/140152987

相关文章

  • IDEA运行时报错:Application Server was not connected before run configuration stop
    求求了,有没有大佬能看到呀,马上就考试了,运行不出来真的好烦躁无力呀,我在CSDN上看到了好多解决方法,但是我用过之后依旧没能解决。这是我的tomcat和jdk版本,版本应该没有问题吧,这也是老师发给我们的版本这是我的环境变量的配置; 这是我的tomca,jdk,以及IDEA的地址;  求......
  • RuoYi-Cloudv3.6.4使用教程【2】新增子模块_使用代码生成功能,创建功能页面
    目录准备工作修改代码生成的配置信息ry-cloud中创建表代码生成使用导入对应表代码生成代码放置菜单启动新增模块创建数据库创建表创建配置文件_新增的模块新增logback.xml新增banner添加路由启动项目✨接新增子模块,让子模块运行起来,还没创建模块的移步这里:RuoYi-Cl......
  • Financial Analysis with Python
    Project1OverviewandfilesProject1PleasereviewallthematerialfromthefollowingLecturesbeforecompletingthisassessment:Lecture1-FinancialAnalysiswithPython:DownloadingStockPricesLecture2-Python:TheBuildingBlocksLecture3-P......
  • conda 源设置方法总结
    conda源设置有2种方法。1是直接在命令行设置。2是使用配置文件.condarc中写入配置频道。命令行设置condaconfig--addchannelshttps://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/freecondaconfig--addchannelshttps://mirrors.tuna.tsinghua.edu.cn/anaconda/......
  • C_THQ_ch3
    //用函数printf()输出数据,函数scanf()输入数据//必须指定输入输出数据的格式,不同类型的数据指定不同的格式//初学不必深究,重点掌握常用规则,其他随时查表#include<stdio.h>intmain(void){inta=1,b=2;//函数printf()一般格式:printf(格式控制,输出表列)//格式控制:双撇号括起......
  • C++ 基础的输入输出介绍
    C++基础的输入输出介绍在C++编程的世界中,输入输出是连接程序与用户界面的桥梁,是实现人机交互不可或缺的部分。对于初学者而言,掌握C++中基本的输入输出方式——使用cin进行输入和使用cout进行输出,是踏入C++编程大门的第一步。本文将详细介绍如何在C++程序中利用cin和cout来......
  • AIGC最大价值不是降本,而是利用内容杠杆增效
    在这个信息爆炸的时代,人工智能生成内容(AIGC)技术的崛起引发了广泛讨论。表面上,许多人将AIGC视为一种降低成本的工具。然而,如果我们以纳瓦尔·拉维坎特的视角来审视,就会发现AIGC的真正价值在于它作为一种强大的知识杠杆,能够exponentially增加我们的学习和创新能力。纳瓦尔......
  • 【漏洞复现】Geoserver XPath表达式注入致远程代码执行漏洞(CVE-2024-36401)
    0x01产品简介GeoServer是一个开源服务器,用于共享、处理和编辑地理空间数据。它支持多种地图和数据标准,使用户能够通过网络访问和操作地理信息系统(GIS)数据。0x02漏洞概述2024年7月,互联网上披露Geoserver表达式注入致远程代码执行漏洞(CVE-2024-36401),攻击者无需认证即可利......
  • Facebook广告被拒:常见原因以及避免屏蔽的方法
    大多数情况下,广告被屏蔽是因为违反了规则,这不仅仅是因为审核因素。有些规则并不明显,也没有在任何地方指定。例如,在广告中使用广告政策中未列出的停用词;审核算法确定照片描绘的模特过于暴露。下面小编将为你介绍Facebook广告的踩雷点,帮助大家切实做好投放工作。一、广告被拒绝......
  • C++ UTF-8编解码
    icu编解码数据:externconstUConverterSharedData  _MBCSData,_Latin1Data,  _UTF8Data,_UTF16BEData,_UTF16LEData,_UTF32BEData,_UTF32LEData,  _ISO2022Data,   _LMBCSData1,_LMBCSData2,_LMBCSData3,_LMBCSData4,_LMBCSData5,_LMBCSData6......