1、字符串的常见方法
1.1 Format:格式化
String name = "陈晨";
int age = 18;
String message = "大家好,我是{0},我今年{1}岁";
Console.WriteLine(string.Format(message, name, age));//格式化,有几个占位符就需要几个参数,占位符的顺序也必须一致
1.2 IsNullOrEmpty和IsNullOrWhiteSpace:IsNullOrEmpty用于判断是否为null或者empty(空串""),IsNullOrWhiteSpace既可以实现前者的判断也可以判断是否有空格(" ")。
String username = "chenchen";
String password = "123456";
if (String.IsNullOrEmpty(username))
{
throw new ArgumentException("username is null");
}
else
{
if (String.IsNullOrEmpty(password))
{
throw new ArgumentException("password is null");
}
}
Console.WriteLine("登陆成功!");
我们用IsNullOrEmpty作为示例(IsNullOrWhiteSpace同理),当运行以上代码判断用户账号密码是否正确时,如果输入正确的账号密码就会打印出登陆成功,但是此时如果修改将String username = "chenchen";修改为String username = "";就会出现以下报错:
1.3 Equals:判断是否相等
String str = "Hello";
//if(str.ToLower()=="hello")
//大小写敏感
if (str.ToLower().Equals("hello"))
{
Console.WriteLine("相等");
}
else
{
Console.WriteLine("不相等");
}
由于Equals对大小写敏感,这里使用ToLower对其转化为统一的格式。
1.4 Contains:判断是否包含,也同样对大小写敏感。
String str = "Hello World!";
if (str.Contains("x"))
{
Console.WriteLine("包含");
}
else
{
Console.WriteLine("不包含");
}
1.5 Length:计算字符串的长度。在C#中中文和英文同样只占据一个字节
String str = "Hello World!你好";
Console.WriteLine(str.Length);//中文只占一个字符
//输出结果为14
1.6 Substring:截取字符串
String str = "Hello World!你好";
//Console.WriteLine(str.Length);//中文只占一个字符
Console.WriteLine(str.Substring(0));//从索引为0开始截取
//输出结果为--Hello World!你好
Console.WriteLine(str.Substring(0, 5));//从索引为0开始,截取5个
//输出结果为--Hello
Console.WriteLine(str.Substring(6, 5));//从中间开始截取,截取五个字符
//输出结果为--World
Console.WriteLine(str.Substring(str.Length - 2));//截取最后的字符
//输出结果为--你好
1.7 IndexOf和LastIndexOf:用于搜索某一字符的位置,返回的结果是其索引,IndexOf是从前往后找,LastIndexOf是从后往前找。
String path = "C:\\Users\\lenovo\\Desktop\\笔记\\C#\\课堂:笔记.docx";//第一个\是语言的转义字符,第二个\是真正的\字符
Console.WriteLine(path);
Console.WriteLine(path.IndexOf(":"));
Console.WriteLine(path.LastIndexOf(":"));
/*输出结果为:
C:\Users\lenovo\Desktop\笔记\C#\课堂:笔记.docx
1
32*/
String path = "C:\\Users\\lenovo\\Desktop\\笔记\\C#\\课堂笔记.docx";
//使用实例:
int pos = path.LastIndexOf("\\");
int dotpos = path.LastIndexOf(".");
//打印文件路径
string dir = path.Substring(0, pos);
Console.WriteLine(dir);
//打印文件名,带后缀
string filename = path.Substring(pos + 1);
Console.WriteLine(filename);
//打印文件名,不带后缀
Console.WriteLine(filename.Substring(0, dotpos - pos - 1));
//打印文件类型
Console.WriteLine(path.Substring(dotpos));
Console.WriteLine(path.Substring(dotpos + 1));
/*
输出结果:
C:\Users\lenovo\Desktop\笔记\C#
课堂笔记.docx
课堂笔记
.docx
docx
*/
1.8 StartsWith 和 EndsWith:判断是否以什么开始,判断是否以什么结尾。
String path = "C:\\Users\\lenovo\\Desktop\\笔记\\C#\\课堂笔记.docx";
if (path.StartsWith("C:\\Users\\lenovo\\Desktop\\笔记"))
{
Console.WriteLine("属于");//判断是否属于该路径下的文件
}
string extname = path.Substring(path.LastIndexOf("."));
Console.WriteLine("扩展名:{0}", extname);
if (path.EndsWith(".docx"))
{
Console.WriteLine("world文件");
}
else if (path.EndsWith(".jpg"))
{
Console.WriteLine("图片文档");
}
else if (path.EndsWith(".mp4"))
{
Console.WriteLine("视频文档");
}
1.9 Remove:删除部分字符串
String path = "C:\\Users\\lenovo\\Desktop\\笔记\\C#\\课堂笔记.docx";
Console.WriteLine(path.Remove(path.LastIndexOf(".")));//删除指定位置后面的内容
Console.WriteLine(path.Remove(path.LastIndexOf("."), 1));//删除中间内容
/*
输出结果:
C:\Users\lenovo\Desktop\笔记\C#\课堂笔记
C:\Users\lenovo\Desktop\笔记\C#\课堂笔记docx
*/
1.10 Reserve:对字符串进行翻转。
string str = "我的骄傲";
Console.WriteLine(str.Reverse().ToArray());
//输出结果:傲骄的我
1.11 Trim:删除字符串两侧的空格。若要删除字符中间的空格则需要用replace将空格替换掉。
string str = " 我的 骄傲 ";
Console.WriteLine("-" + str + "-");
Console.WriteLine("-" + str.Trim() + "-");//删除两侧空格
Console.WriteLine("-" + str.Replace(" ", "") + "-");//删除所有的空格
/*
输出结果:
- 我的 骄傲 -
-我的 骄傲-
-我的骄傲-
*/
1.12 ToUpper和ToLower:全部转大写和全部转小写。
1.13 Concat:拼接字符串。
string str = "hello World";
Console.WriteLine(str.ToUpper());//全部转大写
Console.WriteLine(str.ToLower());//全部转小写
str = str.Replace(" ", "");
//大驼峰:HelloWorld
string first = str.Substring(0, 1);
Console.WriteLine(first.ToUpper() + str.Substring(1));
Console.WriteLine(string.Concat(first.ToUpper(), str.Substring(1)));//两种拼接方式
//小驼峰:helloWorld
Console.WriteLine(first.ToLower() + str.Substring(1));
Console.WriteLine(string.Concat(first.ToLower(), str.Substring(1)));
/*
输出结果:
HELLO WORLD
hello world
HelloWorld
HelloWorld
helloWorld
helloWorld
*/
1.14 Jion和Split:根据分隔符将字符进行连接或者分割。
string[] names = { "刘备", "张飞", "关羽" };
string str = "";
//转换成一个字符串
for (int i = 0; i < names.Length; i++)
{
str += string.Concat(names[i], ",");
}
str = str.Remove(str.Length - 1);//去掉多余的逗号
Console.WriteLine(str);
//用join转换成字符串
Console.WriteLine(string.Join("|", names));//第一个参数是分隔符,第二个参数是数组
string city = "北京,上海,深圳,广州,杭州";
//变成一个数组
string[] citis = city.Split(',');
foreach (string s in citis)
{
Console.WriteLine(s);
}
/*
输出结果:
刘备,张飞,关羽
刘备|张飞|关羽
北京
上海
深圳
广州
杭州
*/
2、实现身份证的解析
身份证号码是由18位数字组成的,前6位数字分别代表户籍所在省、市、区县的编号。7-14位数字表示:出生年月日。15-16是所在地派出所代码。第17位代表的是性别,奇数代表男性,偶数代表女性。第18位是校验码。
string num = "123456202407231521";
//前六位户籍所在地
Console.WriteLine("户籍所在地:"+num.Substring(0,6));
//出生年月
string birthday_year = num.Substring(6,4);
string birthday_month = num.Substring(10,2);
string birthday_day = num.Substring(12,2);
/*Console.WriteLine(birthday_year);
Console.WriteLine(birthday_month);
Console.WriteLine(birthday_day);*/
string birthday = "出生日期:{0}年{1}月{2}日";
Console.WriteLine(string.Format(birthday,birthday_year,birthday_month,birthday_day));
//顺序码
string order= num.Substring(14, 2);
Console.WriteLine("所在派出所代码:{0}",order);
//性别
string gender = num.Substring(num.Length-2,1);
int int_ge = int.Parse(gender);
if (int_ge % 2 == 0)
{
Console.WriteLine("性别:女");
}
else
{
Console.WriteLine("性别:男");
}
Console.WriteLine("校验码:{0}",num.Substring(num.Length-1));
输出结果为:
3、遍历磁盘,列出目录和文件、统计文件个数,统计不同类型(后缀)的文件个数
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
static void Main(string[] args)
{
string rootDirectory = @"D:\";
// 调用函数,并输出结果
var stats = TraverseDirectory(rootDirectory);
// 输出总文件数
Console.WriteLine($"Total files: {stats.TotalFiles}");
// 输出不同类型文件的统计信息
foreach (var kvp in stats.FileTypeCounts)
{
Console.WriteLine($"Extension: {kvp.Key}, Count: {kvp.Value}");
}
}
static (int TotalFiles, Dictionary<string, int> FileTypeCounts) TraverseDirectory(string root)
{
var totalFiles = 0;
var fileTypeCounts = new Dictionary<string, int>();
// 遍历目录
Traverse(root, ref totalFiles, fileTypeCounts);
return (totalFiles, fileTypeCounts);
}
static void Traverse(string directory, ref int totalFiles, Dictionary<string, int> fileTypeCounts)
{
try
{
// 获取目录中的文件和子目录
string[] directories = Directory.GetDirectories(directory);
string[] files = Directory.GetFiles(directory);
// 遍历文件
foreach (string file in files)
{
totalFiles++;
string extension = Path.GetExtension(file)?.ToLowerInvariant() ?? "";
if (!fileTypeCounts.ContainsKey(extension))
{
fileTypeCounts[extension] = 0;
}
fileTypeCounts[extension]++;
}
// 递归遍历子目录
foreach (string dir in directories)
{
Traverse(dir, ref totalFiles, fileTypeCounts);
}
}
catch (Exception ex)
{
// 捕获并处理异常,例如权限不足
Console.WriteLine($"Error accessing {directory}: {ex.Message}");
}
}
}
输出结果: