首页 > 编程语言 >C#的学习基础篇(3)——字符串的常见方法

C#的学习基础篇(3)——字符串的常见方法

时间:2024-07-05 16:31:03浏览次数:20  
标签:Console string C# 常见 str WriteLine 字符串 path

目录

1. 字符串的常见方法

        1.1 Format 

        1.2 IsNullOrEmpty

        1.3 IsNullOrWhiteSpace

        1.4 Equals

        1.5 Contains

        1.6 Length

        1.7 Substring

        1.8  IndexOf & LastIndexOf

        1.9 StartsWith & EndsWith 

        1.10 Remove

        1.11 Reverse

        1.12 Trim

        1.13 ToLower & ToUpper

        1.14 Replace

        1.15 Concat

        1.16  Join

        1.17 Split

2. 实现身份证的解析(练习字符串方法)

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


1. 字符串的常见方法

        字符串的常见方法有17个,如下所示

       1.1 Format (格式化字符串)
String name = "五六七";
int age = 21;
String message = "大家好,我是{0},我今年{1}岁";
Console.WriteLine(string.Format(message, name, age));
        1.2 IsNullOrEmpty(检查一个字符串是否为null或长度为零即空字符串""
string username = "user";
string password = "000000";

if (string.IsNullOrEmpty(username))
{
    throw new ArgumentNullException("username is null");

}
else
{
    if (string.IsNullOrEmpty(password))
    {
        throw new ArgumentNullException("password is null");
    }
}
Console.WriteLine("登录成功!");
        1.3 IsNullOrWhiteSpace(方法检查一个字符串是否为null、空字符串""或仅包含空白字符,如空格、制表符、换行符等)
string username = "user";
string password = "000000";

if (string.IsNullOrWhiteSpace(username))
{
    throw new ArgumentNullException("username is null");

}
else
{
    if (string.IsNullOrWhiteSpace(password))
    {
        throw new ArgumentNullException("password is null");
    }
}
Console.WriteLine("登录成功!");
         1.4 Equals(比较当前字符串与另一个字符串是否相等)
string str = "Hello";

if (str.Equals("hello"))
{
    Console.WriteLine("相等");

}
else
{
    Console.WriteLine("不相等");
}
        1.5 Contains(判断当前字符串是否包含指定的子字符串)
string str = "Hello world";
if (str.Contains("hello"))
{
    Console.WriteLine("包含");
}
else
{
    Console.WriteLine("不包含");
}
        1.6 Length(获取字符串长度)
string str = "Hello world";
Console.WriteLine(str.Length);
        1.7 Substring(从哪个位置开始,截取多少位)(截取字符串,获取字符串的一部分,一个参数时截取到最后)
string str = "hello world.你好";

Console.WriteLine(str.Substring(1));

Console.WriteLine(str.Substring(6, 5));
        1.8  IndexOf & LastIndexOf(找到某个字符串的位置,IndexOf 从前往后、LastIndexOf从后往前)
string path = "C:\\Users\\86157\\Desktop\\C#\\课堂笔记3.docx";

Console.WriteLine(path);
Console.WriteLine(path.IndexOf(":"));
Console.WriteLine(path.LastIndexOf("#"));
        1.9 StartsWith & EndsWith (判断当前字符串是否以指定的字符串开头和判断当前字符串是否以指定的字符串结尾)
string path = "C:\\Users\\86157\\Desktop\\C#\\课堂笔记3.docx";

if (path.StartsWith("C:\\Users\\86157\\Desktop\\C#"))
{
    Console.WriteLine("C#下的文件");
}
string extName = path.Substring(path.LastIndexOf(".") + 1);
Console.WriteLine("扩展名:{0}", extName);

if (path.EndsWith(".docx"))
{
    Console.WriteLine("word文档");

}
else if (path.EndsWith(".jpg"))
{
    Console.WriteLine("tu");

}
        1.10 Remove(删除部分字符串)

string path = "abcdefg";

Console.WriteLine(path.Remove(3));
        1.11 Reverse(字符串反转)

        这里特别注意.ToArray()


string str = "asdf";
Console.WriteLine(str.Reverse().ToArray());
        1.12 Trim(删除字符串两边的空格)

        这里使用“-”符号为了更好的展示效果

string str1 = " ada ";
Console.WriteLine("-" + str1.Trim() + "-");
        1.13 ToLower & ToUpper(转小写,转大写)
string str = "hello World";
Console.WriteLine(str.ToLower());
Console.WriteLine(str.ToUpper());
        1.14 Replace(替换)
string str = "五六七";
Console.WriteLine(str.Replace("七", "⑦"));
        1.15 Concat(字符串拼接,+)
string str1 = "我";
string str2 = "love";
string str3 = "你";
Console.WriteLine(string.Concat(str1,str2,str3));
        1.16  Join(用于连接字符串数组)
string[] names = { "你", "wo", "他" };
Console.WriteLine(string.Join("和", names));
        1.17 Split(将当前字符串分割成子字符串数组)
string citystr = "我,爱,你";
string[] cities = citystr.Split(',');
foreach (string city in cities)
{
    Console.WriteLine(city);
}

2. 实现身份证的解析(练习字符串方法)

实现身份证的解析只需三步:

1.1 判断身份证格式

1.2 格式对了解析出生日期

1.3 解析性别

        代码如下:

        创建一个IDCardParser类

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

namespace DjConsoleApp0527
{
    internal class IDCardParser
    {
        public IDCardParser(string ID)
        {
            if (ID.Length != 18)
            {
                Console.WriteLine("你身份证号码对么?老弟!");
                return;
            }
            else
            {
                Console.WriteLine("您的身份号码为:{0}", ID);
            }

            string birthYear = ID.Substring(6, 4);
            string birthMonth = ID.Substring(10, 2);
            string birthDay = ID.Substring(12, 2);
            //出生日期打印
            Console.WriteLine(string.Format("出生日期为:{0}年{1}月{2}日", birthYear, birthMonth, birthDay));

            int genderCode = int.Parse(ID.Substring(16, 1));
            string gender = genderCode % 2 == 0 ? "女" : "男";
            Console.WriteLine(string.Format("性别:{0}", gender));
        }
    }
}

        调用方法:

using DjConsoleApp0527;

string ID = "000000200304070012";
IDCardParser iDCard = new IDCardParser();
iDCard.IDCard(ID);

        结果:

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

        定义一个DirectoryTraversal类

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

namespace DjConsoleApp0527
{
    class DirectoryTraversal
    {
        public static int totalFiles = 0;
        public void TraverseDirectory(string path, Dictionary<string,int> extensionCount )
        {
            try
            {
                // 获取当前目录下的所有子目录
                string[] subdirectories = Directory.GetDirectories(path);
                foreach (string subdirectory in subdirectories)
                {
                    // 递归遍历子目录
                    TraverseDirectory(subdirectory, extensionCount);
                }

                // 获取当前目录下的所有文件
                string[] files = Directory.GetFiles(path);
                foreach (string file in files)
                {
                    // 增加文件数量计数
                    totalFiles++;

                    // 获取文件的后缀名
                    string extension = Path.GetExtension(file);

                    // 更新后缀名计数
                    if (extensionCount.ContainsKey(extension))
                    {
                        extensionCount[extension]++;
                    }
                    else
                    {
                        extensionCount.Add(extension, 1);
                    }
                    
                }
            }
            catch (Exception ex)
            {
                // 异常处理:权限不足或目录不存在等情况
                Console.WriteLine("发生错误: " + ex.Message);
            }
           
        }
    }
 
}

        调用遍历函数:

using DjConsoleApp0527;



string path = @"C:\Users\86157\Desktop\mysql"; // 更改为要遍历的目标目录
DirectoryTraversal directory= new DirectoryTraversal();
Dictionary<string, int> extensionCount = new Dictionary<string, int>(); // 用于存储后缀名及其对应的文件数量

// 开始遍历目录
directory.TraverseDirectory(path, extensionCount);

// 输出总文件数量
Console.WriteLine("总文件数量: " + DirectoryTraversal.totalFiles);

// 输出按后缀名分类的文件数量
Console.WriteLine("按后缀名分类的文件数量:");
foreach (KeyValuePair<string, int> pair in extensionCount)
{
    Console.WriteLine("后缀名: " + pair.Key + ", 文件数量: " + pair.Value);
}

        结果:

  • 注意:string在C#中是一个不可变类型,这意味着所有字符串方法调用都会返回一个新的字符串,而不是修改原始字符串        
  • 总结:字符串的方法还有很多,我上面写的只是常见的,一定要牢记,这些都是非常重要的东西!

标签:Console,string,C#,常见,str,WriteLine,字符串,path
From: https://blog.csdn.net/qq_63873127/article/details/140149166

相关文章

  • C#的学习(4)
    1.整数转换,整数和字符串,字符串和整数之间的转换怎么实现?        1.1整数转字符串    intn=123;//第一种方式:任何类型和字符串连接,结果都是字符串Console.WriteLine(""+n);//第二种方式:通过Convert.ToString()方法进行转换Console.WriteLine(C......
  • 海康SDK报错Structure.getFieldOrder()
    就是你调用的这个结构体以及其引用的其他结构体,可能没有getFieldOrder()的方法,你只要按照顺序把他填上去就好了。比如publicstaticclassNET_DVR_TIMEextendsStructure{//校时结构参数publicintdwYear;//年publicintdwMonth;//月......
  • FAILED: cpu_adam.so /usr/bin/ld: cannot find -lcurand collect2: error: ld retur
    FAILED:cpu_adam.so c++cpu_adam.ocpu_adam_impl.o-shared-lcurand-L/home/deeplp/anaconda3/envs/minicpm/lib/python3.10/site-packages/torch/lib-lc10-ltorch_cpu-ltorch-ltorch_python-ocpu_adam.so/usr/bin/ld:cannotfind-lcurandcollect2:error:ld......
  • 虚拟ECU:纯电动汽车发展下的新选择
    ​人类文明的进步是一个不断自我否定、自我超越的过程。21世纪以来,随着科技进步和经济社会发展,能源和交通系统已从独立于自然环境的孤立系统,转变为与自然、技术、社会深度耦合的复杂系统。为实现可持续发展和应对气候变化,世界各国都在积极推进能源结构调整和技术创新,以确保在未来......
  • Python多线程-线程池ThreadPoolExecutor
    1.线程池不是线程数量越多,程序的执行效率就越快。线程也是一个对象,是需要占用资源的,线程数量过多的话肯定会消耗过多的资源,同时线程间的上下文切换也是一笔不小的开销,所以有时候开辟过多的线程不但不会提高程序的执行效率,反而会适得其反使程序变慢,得不偿失。为了防止无尽的线程......
  • 外挂级OCR神器:免费文档解析、表格识别、手写识别、古籍识别、PDF转Word
    TextInTools是一款免费的在线OCR工具,支持快速准确的文字和表格识别,手写、古籍识别,提供PDF转Markdown大模型辅助工具,同时支持PDF、WORD、EXCEL、JPG、PPT等各类格式文件的转化。TextInTools特点免费:所有产品提供每日200页免费额度,覆盖日常使用需求。方便:无需下载安装,PC端......
  • mainCRTStartup WinMainCRTStartup
    assumecs:codesg,ds:datas;str字符必须是13位,所以中间加了两个空格,网上很多代码也避开了这个问题,都是通过加空格,拼写错误,反正加个占位符;否则会输出一堆乱码,实在想不明白是什么原因datassegmentstrdb'HelloWorld!','$'datasendscodesgsegmentmovax,datas......
  • const修饰指针变量和assert断言
    一.const修饰指针变量一般来说,const修饰指针变量,可以放在*的左边,也可以放在*的右边,两个表示方法的意义是不一样的。1.代码1——测试无const修饰的情况voidtest1(){ intn=10; intm=20; int*p=&n; *p=20;//1 p=&m;//2}在这个代码中1和2所在的语句均可以......
  • 【高性能服务器】select模型
      ......
  • Linux 交叉编译(toolchain) ARM aarch64版 libcurl.so 库
    前言全局说明curl是用来访问网络,可以上传下载数据一、说明系统环境:ubunt18.04二、官网下载源码:2.1最新版本https://curl.haxx.se/download.htmlhttps://github.com/curl/curl/releases2.2历史版本https://curl.se/download/2.3变更日志https://curl.se/chan......