字符、字符串
1.字符
占用两个字节,16位,16bit,最小值0,最大值65535
System.Char 等同于 char,如果引用了System命名空间,那么也可以简写成Char
1.1 字段
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Convert.ToInt32(char.MaxValue)); //字符串表示的最大范围,Convert.ToInt32是将二进制转换成十进制
Console.WriteLine(Convert.ToInt32(char.MinValue)); //字符串表示的最小范围,Convert.ToInt32是将二进制转换成十进制
}
}
1.2 静态方法
char chA = 'A';
char ch1 = '1';
string str = "test string";
Console.WriteLine(chA.CompareTo('C')); //-2 (meaning 'A' is 2 less than 'C')
Console.WriteLine(chA.Equals('A')); //"True"
Console.WriteLine(Char.GetNumericValue(ch1)); //"1"
Console.WriteLine(Char.IsControl('\t')); //"True"
Console.WriteLine(Char.IsDigit(ch1)); //"True"
Console.WriteLine(Char.IsLetter(',')); //"False"
Console.WriteLine(Char.IsLower('u')); //"True"
Console.WriteLine(Char.IsNumber(ch1)); //"True"
Console.WriteLine(Char.IsPunctuation('.')); //"True"
Console.WriteLine(Char.IsSeparator(str, 4)); //"True"
Console.WriteLine(Char.IsSymbol('+')); //"True"
Console.WriteLine(Char.IsWhiteSpace(str, 4)); //"True"
Console.WriteLine(Char.Parse("S")); //"S"
Console.WriteLine(Char.ToLower('M')); //"m"
Console.WriteLine('x'.ToString()); //"x"
2. 字符串
string 等价于 System.String 。string是一个不可变字符序列。
//字符串定义
string s1 = "hello";
string s2 = @"\\hello";
Console.Write(new string('*',5)); //*****
//字符串转为字符数组
string s1 = "hello";
char[] chs = s1.ToCharArray();
foreach (var item in chs)
{
Console.WriteLine(item);
}
Console.WriteLine(new string(chs));
//输出
h
e
l
l
o
hello
2.1 null和空字符串
- 空字符串
空字符串是值长度为0的字符串,可以用string.Empty 字段来表示。
判断一个字符串是否长度为0,可以用string.Empty来比较或者使用长度是否为0来判断。
- null
null是指字符串指向null,没有初始化。
判断一个字符串是否为null,可以与null进行比较,或者使用方法string.IsNullOrEmpty来判断字符串是否为null或者空字符串
string empty = "";
Console.WriteLine(string.Empty == empty);
Console.WriteLine("" == empty);
Console.WriteLine(string.IsNullOrEmpty(empty));
string? nullStr = null;
Console.WriteLine(nullStr == null);
Console.WriteLine(nullStr == "");
Console.WriteLine(string.IsNullOrEmpty(nullStr));
//输出
True
True
True
True
False
True
2.2 访问字符串中的字符
string s1 = "times";
char ch = s1[1];
Console.WriteLine(ch);
//输出
i
string实现了IEnumerable< char > ,所以可以用 foreach 遍历它的字符
string s1 = "times";
foreach (var item in s1)
{
Console.Write(item+",");
}
//输出
t,i,m,e,s,
2.3 搜索字符串内的字段
string s1 = "times";
Console.WriteLine(s1.StartsWith("ti"));
Console.WriteLine(s1.EndsWith("se"));
Console.WriteLine(s1.Contains("me"));
Console.WriteLine(s1.IndexOf("se"));
//输出
True
False
True
-1
2.4 字符串的修改方法
string s1 = "helloworld";
Console.WriteLine(s1.Substring(1,4)); //ello
Console.WriteLine(s1.Substring(2)); //lloworld 截取从开始位置以后的所有
Console.WriteLine(s1.Insert(5,"=")); //hello=world
Console.WriteLine(s1.Remove(4,3)); //hellrld
Console.WriteLine(s1.PadLeft(15,'-')); //-----helloworld
Console.WriteLine(s1.Replace('l','o')); //heoooworod
string s2 = "---times---";
Console.WriteLine(s2.TrimStart('-')); //times---
Console.WriteLine(s2.TrimEnd('-')); //---times
Console.WriteLine(s2.Trim('-')); //times
string s3 = " t imes-- - ";
Console.WriteLine(s3.Trim().Length); //10 去掉头尾的空格,得出的字符串长度
string s4 = "How are you?";
string[] s4s = s4.Split();
foreach (var ss in s4s)
{
Console.WriteLine(ss);
}
//输出
//How
//are
//you?
Console.WriteLine(string.Join(" ",s4s)); //How are you?
2.5 字符串格式初体验
string patten = "hello {0},my name is {1}.";
Console.WriteLine(string.Format(patten,"lisi","zhangsan")); //hello lisi,my name is zhangsan.
//C#6 以后可以用插值
string name = "lisi";
Console.WriteLine($"hello, {name}."); //hello,lisi.
string he = "hello";
string ll = "hello";
Console.WriteLine(he==ll); //True
Console.WriteLine(he.Equals(ll)); //True
2.6 字符串的顺序比较
string s1 = "hello";
string s2 = "world";
Console.WriteLine(s1.CompareTo(s2)); //-1
Console.WriteLine(s1.CompareTo("hello")); //0
Console.WriteLine(string.Compare(s1,"Hello",true)); //0 忽略大小写比较
3. StringBuilder类
它是一个可变的字符串,属于System.Text命名空间。内部容量的初始值是16个字符,如果需要添加字符,那么自动调整它的容量,默认是int.MaxValue
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++)
{
//sb.Append(i + ",");
//替换为下面这种最好
sb.Append(i);
sb.Append(",");
}
Console.WriteLine(sb.ToString()); //0,1,2,3,4,5,6,7,8,9,
Console.WriteLine(sb.Insert(2, "nihao")); //0,nihao1,2,3,4,5,6,7,8,9,
Console.WriteLine(sb.Remove(sb.Length-1,1)); //0,nihao1,2,3,4,5,6,7,8,9
Console.WriteLine(sb.Replace(',','+')); //0+nihao1+2+3+4+5+6+7+8+9
日期和时间
System空间下有三个不可变的结构体进行事件表示:DateTime、DateTimeOffset、TimeSpan
1. TimeSpan
创建TimeSpan方法:
- 通过构造器
- 通过调用其中一个静态 From ... 方法
- 通过两个 DateTime相减得到
Console.WriteLine(new TimeSpan(2,30,0)); //02:30:00
Console.WriteLine(TimeSpan.FromHours(2.5)); //02:30:00
Console.WriteLine(TimeSpan.FromHours(-2.5)); //-02:30:00
TimeSpan TheDays = TimeSpan.FromDays(10) - TimeSpan.FromSeconds(1);
Console.WriteLine(TheDays.Days); //9
Console.WriteLine(TheDays.Hours); //23
Console.WriteLine(TheDays.Minutes); //23
Console.WriteLine(TheDays.Seconds); //59
Console.WriteLine(TheDays.Milliseconds); //0
Console.WriteLine(TheDays.TotalDays); //9.999988425925926
Console.WriteLine(TheDays.TotalHours); //239.99972222222223
Console.WriteLine(TheDays.TotalMinutes); //14399.983333333334
Console.WriteLine(TheDays.TotalSeconds); //863999
Console.WriteLine(TheDays.TotalMilliseconds); //863999000
2. DateTime
Console.WriteLine(DateTime.Now); //2024/5/9 10:28:49
Console.WriteLine(DateTimeOffset.Now); //2024/5/9 10:28:49 +08:00
Console.WriteLine(DateTime.UtcNow); //2024/5/9 2:29:40 UTC标准时间
//格式化
string localDate = $"{DateTime.Now.Year}年{DateTime.Now.Month}月{DateTime.Now.Day}日 {DateTime.Now.Hour}:{DateTime.Now.Minute}:{DateTime.Now.Second}";
Console.WriteLine(localDate); //2024年5月9日 10:33:21
随机数Random
Random能够生成类型为byte、integer或者double的伪随机数序列
Random r1 = new Random();
Console.WriteLine(r1.Next(100) + "," + r1.Next(100));
Guid 结构体
Guid 结构体表示一个全局唯一标识符。一个生成是可以肯定为全世界唯一16字节值。
Guid d = Guid.NewGuid();
Console.WriteLine(d.ToString()); //xxxx-xxxx-xxxx-xxxx-xxxx
Guid g1 = new Guid("{xxxx-xxxx-xxxx-xxxx-xxxx}");
Guid g2 = new Guid("xxxx");
Console.WriteLine(g1 == g2); //True
常用类
Console类
常规的Console.WriteLine和Console.ReadLine()略。
//修改前景色,也就是文字的颜色
Console.ForegroundColor = ConsoleColor.Green;
//修改文字背景
Console.BackgroundColor = ConsoleColor.Red;
//光标后移多少个位置
Console.CursorLeft += 30;
//修改控制台的输出流到文件输出流
using (System.IO.TextWriter w = System.IO.File.CreateText("e:\\output.txt"))
{
Console.SetOut(w);
Console.WriteLine(Console.ReadLine());
}
Environment 类
属于System.Environment 。它提供了以下属性
- 文件夹和文件 CurrentDirectory、SystemDirectory、CommandLine
- 计算机和操作系统 MachineName、ProcessorCount、OSVersion、NewLine
- 用户登录 UserName、UserInteractive、UserDomainName
- 诊断信息 TickCount、StackTrace、WorkingSet、Version
- 获取环境变量 GetEnvironmentVariable、GetEnvironmentVariables和SetEnvironmentVariable
Console.WriteLine(Environment.CurrentDirectory);
Console.WriteLine(Environment.SystemDirectory);
Console.WriteLine(Environment.CommandLine);
Console.WriteLine("-------------------");
Console.WriteLine(Environment.MachineName);
Console.WriteLine(Environment.ProcessorCount);
Console.WriteLine(Environment.OSVersion);
Console.WriteLine(Environment.NewLine); //输出一个空行
Console.WriteLine("-------------------");
Console.WriteLine(Environment.UserName);
Console.WriteLine(Environment.UserInteractive);
Console.WriteLine(Environment.UserDomainName);
Console.WriteLine("-------------------");
Console.WriteLine(Environment.TickCount);
Console.WriteLine(Environment.StackTrace);
Console.WriteLine(Environment.WorkingSet);
Console.WriteLine(Environment.Version);