網站首頁 編程語言 正文
一、字符串:
1、訪問String中的字符:
string本身可看作一個Char數組。
string s = "hello world";
for (int i = 0; i < s.Length; i++)
{
Console.WriteLine(s[i]);
}
//或者
foreach (char c in s)
{
Console.WriteLine(c);
}
打散為字符數組(ToCharArray)
string s = "Hello World";
char[] arr = s.ToCharArray(); //
Console.WriteLine(arr[0]); // 輸出數組的第一個元素,輸出"H"
2、截取子串:Substring(startIndex,[length]),包括startIndex處的字符。
string s = "hello world";
Console.WriteLine(s.Substring(3));//lo world
Console.WriteLine(s.Substring(3, 4));//lo w
3、查找子串:IndexOf(subString)、LastIndexOf(subString),Contains(subString)
string s = "hello world";
Console.WriteLine(s.IndexOf("o"));//4
Console.WriteLine(s.LastIndexOf("o"));//7
Console.WriteLine(s.IndexOf('l'));//查找該字符串中的第一次'l'出現位置 2
Console.WriteLine(s.IndexOf('l', 4));//查找該字符串中的第四次'l'出現位置 9
Console.WriteLine(s.IndexOf('l', 5, 6)); //從前向后定位從第5位開始和再數6位位置之間'l'出現的位置; 9
Console.WriteLine(s.Contains("e"));//True
4、左右填充子字符串到指定長度:PadLeft(totalLength,char)、PadRight(totalLength,char)
string s = "hello world";
Console.WriteLine(s.PadLeft(15, '*'));//****hello world
Console.WriteLine(s.PadRight(15, '*'));//hello world****
5、轉化大小寫:ToUpper()、ToLower()
string s = "Hello World";
Console.WriteLine(s.ToUpper());//HELLO WORLD
Console.WriteLine(s.ToLower());//hello world
6、刪除字符串指定位置的字符串片段:Remove(startIndex,length)
string s = "Hello World";
Console.WriteLine(s.Remove(7));//Hello W
Console.WriteLine(s.Remove(7,1));//Hello Wrld
7、替換子字符串:Replace(oldStr,newStr)
string s = "Hello World";
Console.WriteLine(s.Replace("l","*"));//He**o Wor*d
Console.WriteLine(s.Replace("or","*"));//Hello W*ld
8、去掉首尾空白或指定字符:Trim()、TrimStart()、TrimEnd()
string s = " Hello World ";
Console.WriteLine(s.Trim());//"Hello World"
Console.WriteLine(s.TrimStart());// "Hello World "
Console.WriteLine(s.TrimEnd());// " Hello World"
string s1 = "hello Worldhd";
Console.WriteLine(s1.Trim('h','d'));//ello Worl
Console.WriteLine(s1.TrimStart('h','d'));//ello Worldhd
Console.WriteLine(s1.TrimEnd('h','d'));//hello Worl
9、在index前位置插入字符:Insert(index,str)
string s = "Hello World";
Console.WriteLine(s.Insert(6,"測試"));//Hello 測試World
10、將字符串按某個特殊字符(串)進行分割,返回字符串數組:Split(char/char[]/string[],[StringSplitOptions]
string s = "Hello Wor ld ";
Console.WriteLine(s.Split('o'));//"Hell","W", "r ld "
Console.WriteLine(s.Split('e', 'd'));// "H","llo Wor l"," "
Console.WriteLine(s.Split(new string[] { " " }, StringSplitOptions.None));//"Hello","Wor","","ld"," "
Console.WriteLine(s.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries));//"Hello","Wor","ld"
foreach (string sub in s.Split('o'))
{
Console.WriteLine(sub);
}
11、字符串合并
1、String.Concat(str1, str2, …., strn):將n個字符串連接,中間沒有連接符。字符串連接也可以用 ‘+’ 來實現。
2、將字符串列表(string[],IEnumerable<string>)用str將各項串連起來,靜態函數Join(SplitCh, array)
string[] arr = {"Hello”,” World"};
Console.WriteLine(string.Join("*", arr));//Hello*World
3、實例方法StringBuilder.Append
StringBuilder sb =new StringBuilder(); // 聲明一個字符串構造器實例
sb.Append("A"); // 使用字符串構造器連接字符串能獲得更高的性能
sb.Append('B');
Console.WriteLine(sb.ToString());// 輸出"AB"
12、格式化,靜態函數Format(占位符,變量)
string s = "Hello World";
Console.WriteLine(string.Format("I Love \"{0}\"", s));//I Love "Hello World"
Console.WriteLine(string.Format("{0:C}", 120.2));//¥120.20
Console.WriteLine(string.Format("{0:yyyy年MM月dd日}", DateTime.Now));
13、與數字的轉換:
1、Int32.TryParse(string,out bool ):始終不拋異常,返回true/false來說明是否成功解析。string為null返回解析不成功。
int ret = 0;
if (int.TryParse("120.5", out ret))//轉換異常!
{
Console.WriteLine(ret);
}
else
{ Console.WriteLine("轉換異常!"); }
2、Int32.Parse(string):解析不成功會拋出異常。string為null時拋出“值不能為 null。參數名: String”異常。
try
{
Console.WriteLine(int.Parse("120.5"));//輸入字符串的格式不正確
}
catch (Exception e)
{ Console.WriteLine(e.Message); }
3、Convert.ToInt32(string):解析不成功會拋出異常,但是string為null時不拋異常返回0.
try
{
Console.WriteLine(Convert.ToInt32("120.5"));//輸入字符串的格式不正確。
}
catch (Exception e)
{ Console.WriteLine(e.Message); }
14、字符串的比較:
1、Compare()是CompareTo()的靜態版本,返回小于,大于還是等于后者字符串(分別為-1,1,0)
string str1 = "you are very happy!!";
string str2 = "I am very happy!!";
Console.WriteLine( string.Compare(str1, str2));//1
Console.WriteLine(str1.CompareTo(str2));//1
2、CompareOrdinal():對兩字符串比較,而不考慮本地化語言和文化。將整個字符串每5個字符(10個字節)分成一組,然后逐個比較,找到第一個不相同的ASCII碼后退出循環。并且求出兩者的ASCII碼的差。
string str1 = "you are very happy!!";
string str2 = "I am very happy!!";
Console.WriteLine(string.CompareOrdinal(str1, str2));//48
3、Equals()與“==”等價,靜態或實例Equals,返回相等還是不等(true/false).
string str2 = "I am very happy!!";
string str3 = "I am very happy!!";
Console.WriteLine(str2.Equals(str3));//True
Console.WriteLine(str2 == str3);//True
15、字符串的復制
(1)、String.Copy(str):參數str為要復制的字符串,它回返回一個與該字符串相等的字符串?
(2)、SreStr.CopyTo(StartOfSreStr, DestStr, StartOfDestStr, CopyLen):它必須被要復制的字符串實例調用,它可以實現復制其中某一部分到目標字符串的指定位置
string s = "Hello World";
string s1 = String.Copy(s);
Console.WriteLine(s1);//Hello World
char[] s2 = new char[20];
s.CopyTo(2, s2, 0, 8);
Console.WriteLine(s2);//llo Worl000000000000000000000000
16、判斷是否是已某種字符串開始或者結束
string s = "Hello World";
Console.WriteLine(s.StartsWith("He")); // True
Console.WriteLine(s.EndsWith("He")); // False
17、判斷字符是否為null或者為空,返回值為bool;
string s = "Hello World";
string s2 = null;
Console.WriteLine(string.IsNullOrEmpty(s)); // False
Console.WriteLine(string.IsNullOrEmpty(s2)); // True
二、char字符。
1、Char的表示方法:
- 字面法:char a=’x’
- 十六進制法:char a=’\x0058’
- 顯示轉換整數:char a=(char)88
- Unicode形式:char a=’\u0058’
2、轉義字符:
- \n =\u000a 換行符
- \t =\u0009 制表符
- \r =\u000d 回車符
- \“ =\u0022 雙引號
- \' =\u0027 單引號
- \\ =\u005c 反斜杠
- \b =\u0008 退格符
3、char的靜態方法:
- char.IsDigit():是否為十進制數字
- char.IsNumber():數字
- char.IsLetter():字母
- char.IsLetterOrdigt():字母或數組
- char.IsUpper()/IsLower():大小寫字母
- char.IsPunctuation():標點符號
- char.IsSymbol():符號字符
- char.IsControl():控制字符
- char.IsSeprator():分隔符
- char.IsWhiteSpace():空白字符
- char.GetNumberialValue():獲取數字值
- char.ToUpper()/ToLower():更改大小寫
原文鏈接:https://www.cnblogs.com/springsnow/p/9428657.html
相關推薦
- 2022-03-26 c#使用listbox的詳細方法和常見問題解決_C#教程
- 2022-11-25 CentOS?7.9?升級內核?kernel-ml-5.6.14版本的方法_云其它
- 2023-03-26 python3.7環境下sanic-ext未生效踩坑解析_python
- 2022-07-04 Python繪制多因子柱狀圖的實現示例_python
- 2022-09-03 ahooks封裝cookie?localStorage?sessionStorage方法_React
- 2022-08-15 解決多個el-checkbox內容折行對不齊問題(可以限制每行展示的個數)
- 2023-02-12 redis如何清理緩存_Redis
- 2022-10-05 VScode中C++頭文件問題的終極解決方法詳析_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支