C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

步入正題: 歡迎提出更簡單或者效率更高的方法

基礎系列:(這邊重點說說Python,上次講過的東西我就一筆帶過了)

1.輸出+類型轉換

Python寫法:

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

NetCore:

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

2.字符串拼接+ 拼接輸出方式

python:

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

NetCore

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

這次為了更加形象對比,一句一句翻譯成NetCore( 有沒有發現規律,user_str[ user_str.Length-1 ]==》 -1 是最後一個,user_str[ user_str.Length-2 ]==》 -2 是最後一個。python在這方面簡化了 )

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

3.2 python 切片語法 : [start_index:end_index:step] (end_index取不到)

# 切片:[start_index:end_index:step] (end_index取不到)# eg:str[1:4] 取str[1]、str[2]、str[3]# eg:str[2:] 取下標為2開始到最後的元素# eg:str[2:-1] 取下標為2~到倒數第二個元素(end_index取不到)# eg:str[1:6:2] 隔著取~str[1]、str[3]、str[5](案例會詳細說)# eg:str[::-1] 逆向輸出(案例會詳細說,)

來個案例:我註釋部分說的很詳細了,附錄會貼democode的

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

NetCore,其實你用Python跟其他語言對比反差更大,net真的很強大了。補充(對比看就清楚Python的step為什麼是2了,i+=2==》2)

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

方法系列:

# 查找:find,rfind,index,rindex

Python查找推薦你用 find和rfind

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

netcore: index0f 就相當於python裡面的 find

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

# 計數:count

python: str.count()

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

netcore:這個真用基礎來解決的話,只能自己變形一下: (原字符串長度 - 替換後的長度) / 字符串長度

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

Python補充說明:像這些方法練習用 ipython3 就好了( sudo apt-get install ipython3 ),code的話需要一個個的print,比較麻煩(我這邊因為需要寫文章,所以只能一個個code)

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

index查找不到會有異常

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

# 替換:replace

Python: xxx.replace(str1, str2, 替換次數)

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

replace可以指定替換幾次

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

NetCore:替換指定次數的功能有點業餘,就不說了,你可以自行思考哦~

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

#連接:join: eg:print("-".join(test_list))

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

netcore: string.Join(分隔符,數組)

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

#分割:split(按指定字符分割),splitlines(按行分割),partition(以str分割成三部分,str前,str和str後),rpartition

說下split的切片用法 :print( test_input.split(" ",3) ) #在第三個空格處切片,後面的不切了

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

繼續說說 splitlines (按行分割),和split("\n")的區別我圖中給了案例

擴展: split(),默認按空字符切割(空格、\t、\n等等,不用擔心返回'')

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

最後說一下 partitionr partition 返回是元祖類型(後面會說的),方式和find一樣,找到第一個匹配的就罷工了【注意一下沒找到的情況】

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

netcore: split裡面很多重載方法,可以自己去查看下,eg: Split("\n",StringSplitOptions.RemoveEmptyEntries)

再說一下這個: test_str.Split('a');//返回數組 。 如果要和Python一樣 返回列表 ==》test_str.Split('a').ToList() ; 【需要引用linq的命名空間哦】

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

# 頭尾判斷:startswith(以。。。開頭),endswith(以。。。結尾)

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

netcore:

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

# 大小寫系: lower (字符串轉換為小寫), upper (字符串轉換為大寫),title(單詞首字母大寫), capitalize ( 第一個字符大寫,其他變小寫 )

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

netcore:

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

# 格式系列: lstrip (去除左邊空格), rstrip (去除右邊空格), strip (去除兩邊空格)美化輸出系列: ljust , rjust , center

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

netcore: Tirm很強大,除了去空格還可以去除你想去除的任意字符

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

ljust,rjust,center這些就不說了,python經常在linux終端中輸出,所以這幾個用的比較多。net裡面 string.Format 各種格式化輸出,可以參考

# 驗證系列: isalpha (是否是純字母), isalnum (是否是數字|字母), isdigit (是否是純數字), isspace (是否是純空格)

一張圖搞定,其他的自己去試一試吧,注意哦~ test_str5=" \t \n " # isspace() ==>true

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

netcore: string. IsNullOrEmpty 和 string. IsNullOrWhiteSpace 是系統自帶的,其他的你需要自己封裝一個擴展類(eg: 簡單封裝 )【附錄有】

C 風靡一時的編程語言和現在最火編程語言Python!誰更強?

附錄:

Python3:

# #輸出+類型轉換# user_num1=input("輸入第一個數:")# user_num2=input("輸入第二個數:")# print("兩數之和:%d"%(int(user_num1)+int(user_num2)))# # ------------------------------------------------------------# #字符串拼接# user_name=input("輸入暱稱:")# user_pass=input("輸入密碼:")# user_url="192.168.1.121"# #拼接輸出方式一:# print("ftp://"+user_name+":"+user_pass+"@"+user_url)# #拼接輸出方式二:# print("ftp://%s:%s@%s"%(user_name,user_pass,user_url))# # -------------------------------------------------------------# # 字符串遍歷、下標、切片# user_str="七大姑曰:工作了嗎?八大姨問:買房了嗎?異性說:結婚了嗎?"# #遍歷# for item in user_str:# print(item,end=" ")# #長度:len(user_str)# print(len(user_str))# #第一個元素:user_str[0]# print(user_str[0])# #最後一個元素:user_str[-1]# print(user_str[-1])# print(user_str[len(user_str)-1])#其他編程語言寫法# #倒數第二個元素:user_str[-2]# print(user_str[-2])# # -------------------------------------------------------------# 切片:[start_index:end_index:step] (end_index取不到)# eg:str[1:4] 取str[1]、str[2]、str[3]# eg:str[2:] 取下標為2開始到最後的元素# eg:str[2:-1] 取下標為2~到倒數第二個元素(end_index取不到)# eg:str[1:6:2] 隔著取~str[1]、str[3]、str[5](案例會詳細說)# eg:str[::-1] 逆向輸出(案例會詳細說,)it_str="我愛編程,編程愛它,它是程序,程序是誰?"#eg:取“編程愛它” it_str[5:9]print(it_str[5:9])print(it_str[5:-11]) #end_index用-xx也一樣print(it_str[-15:-11])#start_index用-xx也可以#eg:取“編程愛它,它是程序,程序是誰?” it_str[5:]print(it_str[5:])#不寫默認取到最後一個#eg:一個隔一個跳著取("我編,程它它程,序誰") it_str[0::2]print(it_str[0::2])#step=△index(eg:0,1,2,3。這裡的step=> 2-0 => 間隔1)#eg:倒序輸出 it_str[::-1]# end_index不寫默認是取到最後一個,是正取(從左往右)還是逆取(從右往左),就看step是正是負print(it_str[::-1])print(it_str[-1::-1])#等價於上一個# # -------------------------------------------------------------View Codetest_str="ABCDabcdefacddbdf"# -------------------------------------------------------------# # 查找:find,rfind,index,rindex# # xxx.find(str, start, end)# print(test_str.find("cd"))#從左往右# print(test_str.rfind("cd"))#從右往左# print(test_str.find("dnt"))#find和rfind找不到就返回-1# # index和rindex用法和find一樣,只是找不到會報錯(以後用find系即可)# # print(test_str.index("dnt"))# # -------------------------------------------------------------# # 計數:count# # xxx.count(str, start, end)# print(test_str.count("a"))# # -------------------------------------------------------------# # 替換:replace# # xxx.replace(str1, str2, count_num)# print(test_str)# print(test_str.replace("b","B"))#並沒有改變原字符串,只是生成了一個新的字符串# print(test_str)# # replace可以指定替換幾次# print(test_str.replace("b","B",1))#ABCDaBcdefacddbdf# # -------------------------------------------------------------# 分割:split(按指定字符分割),splitlines(按行分割),,partition(以str分割成三部分,str前,str和str後),rpartition# test_list=test_str.split("a")#a有兩個,按照a分割,那麼會分成三段,返回類型是列表(List),並且返回結果中沒有a# print(test_list)# test_input="hi my name is dnt"# print(test_input.split(" ")) #返回列表格式(後面會說)['hi', 'my', 'name', 'is', 'dnt']# print(test_input.split(" ",3))#在第三個空格處切片,後面的不管了# # 按行分割,返回類型為List# test_line_str="abc\nbca\ncab\n"# print(test_line_str.splitlines())#['abc', 'bca', 'cab']# print(test_line_str.split("\n"))#看出區別了吧:['abc', 'bca', 'cab', '']# # 沒看出來就再來個案例# test_line_str2="abc\nbca\ncab\nLLL"# print(test_line_str2.splitlines())#['abc', 'bca', 'cab', 'LLL']# print(test_line_str2.split("\n"))#再提示一下,最後不是\n就和上面一樣效果# 擴展:# print("hi my name is dnt\t\n m\n\t\n".split())#split(),默認按空字符切割(空格、\t、\n等等,不用擔心返回'')# #partition,返回是元祖類型(後面會說的),方式和find一樣,找到第一個匹配的就罷工了# print(test_str.partition("cd"))#('ABCDab', 'cd', 'efacddbdf')# print(test_str.rpartition("cd"))#('ABCDabcdefa', 'cd', 'dbdf')# print(test_str.partition("感覺自己萌萌噠"))#沒找到:('ABCDabcdefacddbdf', '', '')# # -------------------------------------------------------------# # 連接:join# # separat.join(xxx)# # 錯誤用法:xxx.join("-")# print("-".join(test_list))# # -------------------------------------------------------------# # 頭尾判斷:startswith(以。。。開頭),endswith(以。。。結尾)# # test_str.startswith(以。。。開頭)# start_end_str="http://www.baidu.net"# print(start_end_str.startswith("https://") or start_end_str.startswith("http://"))# print(start_end_str.endswith(".com"))# # -------------------------------------------------------------# # 大小寫系:lower(字符串轉換為小寫),upper(字符串轉換為大寫),title(單詞首字母大寫),capitalize(第一個字符大寫,其他變小寫)# print(test_str)# print(test_str.upper())#ABCDABCDEFACDDBDF# print(test_str.lower())#abcdabcdefacddbdf# print(test_str.capitalize())#第一個字符大寫,其他變小寫# # -------------------------------------------------------------# # 格式系列:lstrip(去除左邊空格),rstrip(去除右邊空格),strip(去除兩邊空格),ljust,rjust,center# strip_str=" I Have a Dream "# print(strip_str.strip()+"|")#我加 | 是為了看清後面空格,沒有別的用處# print(strip_str.lstrip()+"|")# print(strip_str.rstrip()+"|")# #這個就是格式化輸出,就不講了# print(test_str.ljust(50))# print(test_str.rjust(50))# print(test_str.center(50))# # -------------------------------------------------------------# 驗證系列:isalpha(是否是純字母),isalnum(是否是數字|字母),isdigit(是否是純數字),isspace(是否是純空格)# test_str2="Abcd123"# test_str3="123456"# test_str4=" \t"# test_str5=" \t \n " #isspace() ==>true# 一張圖搞定,其他的自己去試一試吧# test_str.isalpha()# test_str.isalnum()# test_str.isdigit()# test_str.isspace()View Code 

NetCore:

using System;using System.Linq;namespace aibaseConsole{ public static class Program { private static void Main() { #region BaseCode //var test="123";//定義一個變量 // Console.WriteLine(test);//輸出這個變量 // // Console.WriteLine("請輸入用戶名:"); // var name = Console.ReadLine(); //  // Console.WriteLine("請輸入性別:"); // var gender = Console.ReadLine(); //  // Console.WriteLine($"Name:{name},Gender:{gender}"); //推薦用法 // Console.WriteLine("Name:{0},Gender:{1}", name, gender); //Old 輸出 // //// 類型轉換 // Console.WriteLine("輸入第一個數字:");  // var num1 = Console.ReadLine();  // Console.WriteLine("輸入第二個數字:");  // var num2 = Console.ReadLine(); // Console.WriteLine($"num1+num2={Convert.ToInt32(num1)+Convert.ToInt32(num2)}"); //  //// Convert.ToInt64(),Convert.ToDouble(),Convert.ToString() // Console.Write("dnt.dkill.net/now"); // Console.WriteLine("帶你走進中醫經絡"); // // var temp = "xxx"; // var tEmp = "==="; // Console.WriteLine(temp + tEmp); // var num = 9; // Console.WriteLine("num=9,下面結果是對2的除,取餘,取商操作:"); // Console.WriteLine(num/2.0); // Console.WriteLine(num%2.0); // Console.WriteLine(num/2); // //指數 // Console.WriteLine(Math.Pow(2,3)); // int age = 24; // // if (age >= 23) // Console.WriteLine("七大姑曰:工作了嗎?八大姨問:買房了嗎?異性說:結婚了嗎?"); // else if (age >= 18) // { // Console.WriteLine(age); // Console.WriteLine("成年了哇"); // } // else // Console.WriteLine("好好學習天天向上"); // int i = 1; // int sum = 0; // while (i <= 100) // { // sum += i; // i++; // } // Console.WriteLine(sum); // var name = "https://pan.baidu.com/s/1weaF2DGsgDzAcniRzNqfyQ#mmd"; // foreach (var i in name) // { // if(i=='#') // break; // Console.Write(i); // } // Console.WriteLine("\n end ..."); #endregion #region String // //# # 字符串遍歷、下標、切片 // //# user_str="七大姑曰:工作了嗎?八大姨問:買房了嗎?異性說:結婚了嗎?" // var user_str = "七大姑曰:工作了嗎?八大姨問:買房了嗎?異性說:結婚了嗎?"; // // //# #遍歷 // //# for item in user_str: // //# print(item,end=" ") // foreach (var item in user_str) // { // Console.Write(item); // } //  // //# #長度:len(user_str) // //# print(len(user_str)) // Console.WriteLine(user_str.Length); // // //# #第一個元素:user_str[0] // //# print(user_str[0]) // Console.WriteLine(user_str[0]); //  // //# #最後一個元素:user_str[-1] // //# print(user_str[-1]) // //# print(user_str[len(user_str)-1])#其他編程語言寫法 // Console.WriteLine(user_str[user_str.Length-1]); // // // //# #倒數第二個元素:user_str[-2] // //# print(user_str[-2]) // Console.WriteLine(user_str[user_str.Length-2]); // //# # ------------------------------------------------------------- // // // //# 切片:[start_index:end_index:step] (end_index取不到) // //# eg:str[1:4] 取str[1]、str[2]、str[3] // //# eg:str[2:] 取下標為2開始到最後的元素 // //# eg:str[2:-1] 取下標為2~到倒數第二個元素(end_index取不到) // //# eg:str[1:6:2] 隔著取~str[1]、str[3]、str[5](案例會詳細說) // //# eg:str[::-1] 逆向輸出(案例會詳細說,) // // // var it_str = "我愛編程,編程愛它,它是程序,程序是誰?"; // // // //#eg:取“編程愛它” it_str[5:9] // // print(it_str[5:9]) // // print(it_str[5:-11]) #end_index用-xx也一樣 // // print(it_str[-15:-11])#start_index用-xx也可以 //  // //Substring(int startIndex, int length) // Console.WriteLine(it_str.Substring(5, 4));//第二個參數是長度 //  // // // //#eg:取“編程愛它,它是程序,程序是誰?” it_str[5:] // // print(it_str[5:])#不寫默認取到最後一個 // Console.WriteLine(it_str.Substring(5));//不寫默認取到最後一個 //  // //#eg:一個隔一個跳著取("我編,程它它程,序誰") it_str[0::2] // // print(it_str[0::2])#step=△index(eg:0,1,2,3。這裡的step=> 2-0 => 間隔1) //  // //這個我第一反應是用linq ^_^ // for (int i = 0; i < it_str.Length; i+=2)//對比看就清除Python的step為什麼是2了,i+=2==》2 // { // Console.Write(it_str[i]); // } //  // Console.WriteLine("\n倒序:"); // //#eg:倒序輸出 it_str[::-1] // //# end_index不寫默認是取到最後一個,是正取(從左往右)還是逆取(從右往左),就看step是正是負 // // print(it_str[::-1]) // // print(it_str[-1::-1])#等價於上一個 // for (int i = it_str.Length-1; i>=0; i--) // { // Console.Write(it_str[i]); // } // //其實可以用Linq:Console.WriteLine(new string(it_str.ToCharArray().Reverse().ToArray())); #endregion #region StringMethod // var test_str = "ABCDabcdefacddbdf"; // //# # 查找:find,rfind,index,rindex // //# # xxx.find(str, start, end) // //# print(test_str.find("cd"))#從左往右 // Console.WriteLine(test_str.IndexOf('a'));//4 // Console.WriteLine(test_str.IndexOf("cd"));//6 // //# print(test_str.rfind("cd"))#從右往左 // Console.WriteLine(test_str.LastIndexOf("cd"));//11 // //# print(test_str.find("dnt"))#find和rfind找不到就返回-1 // Console.WriteLine(test_str.IndexOf("dnt"));//-1 // //# # index和rindex用法和find一樣,只是找不到會報錯(以後用find系即可) // //# print(test_str.index("dnt")) // //# # ------------------------------------------------------------- // //# # 計數:count // //# # xxx.count(str, start, end) // // print(test_str.count("d"))#4 // // print(test_str.count("cd"))#2 // // 第一反應,字典、正則、linq,後來想怎麼用基礎知識解決,於是有了這個~(原字符串長度-替換後的長度)/字符串長度 // System.Console.WriteLine(test_str.Length-test_str.Replace("d","").Length);//統計單個字符就簡單了 // System.Console.WriteLine((test_str.Length-test_str.Replace("cd","").Length)/"cd".Length); // System.Console.WriteLine(test_str);//不用擔心原字符串改變(python和C#都是有字符串不可變性的) // //# # ------------------------------------------------------------- // // // //# # 替換:replace // //# # xxx.replace(str1, str2, count_num) // //# print(test_str) // //# print(test_str.replace("b","B"))#並沒有改變原字符串,只是生成了一個新的字符串 // //# print(test_str) // System.Console.WriteLine(test_str.Replace("b","B")); // //# # replace可以指定替換幾次 // //# print(test_str.replace("b","B",1))#ABCDaBcdefacddbdf // // 替換指定次數的功能有點業餘,就不說了 // //# # ------------------------------------------------------------- // //# 分割:split(按指定字符分割),splitlines(按行分割),partition(以str分割成三部分,str前,str和str後),rpartition // //# test_list=test_str.split("a")#a有兩個,按照a分割,那麼會分成三段,返回類型是列表(List),並且返回結果中沒有a // //# print(test_list) // var test_array = test_str.Split('a');//返回數組(如果要返回列表==》test_str.Split('a').ToList();) // var test_input = "hi my name is dnt"; // //# print(test_input.split(" ")) #返回列表格式(後面會說)['hi', 'my', 'name', 'is', 'dnt'] // test_input.Split(" "); // //# print(test_input.split(" ",3))#在第三個空格處切片,後面的不管了 // //# # 按行分割,返回類型為List // var test_line_str = "abc\nbca\ncab\n"; // //# print(test_line_str.splitlines())#['abc', 'bca', 'cab'] // test_line_str.Split("\n", StringSplitOptions.RemoveEmptyEntries); // //# print(test_line_str.split("\n"))#看出區別了吧:['abc', 'bca', 'cab', ''] // // // //# # # 沒看出來就再來個案例 // //# test_line_str2="abc\nbca\ncab\nLLL" // //# print(test_line_str2.splitlines())#['abc', 'bca', 'cab', 'LLL'] // //# print(test_line_str2.split("\n"))#再提示一下,最後不是\n就和上面一樣效果 // // // //# # 擴展: // //# print("hi my name is dnt\t\n m\n\t\n".split())#split(),默認按空字符切割(空格、\t、\n等等,不用擔心返回'') // // // //# #partition,返回是元祖類型(後面會說的),方式和find一樣,找到第一個匹配的就罷工了 // //# print(test_str.partition("cd"))#('ABCDab', 'cd', 'efacddbdf') // //# print(test_str.rpartition("cd"))#('ABCDabcdefa', 'cd', 'dbdf') // //# print(test_str.partition("感覺自己萌萌噠"))#沒找到:('ABCDabcdefacddbdf', '', '') // // // //# # ------------------------------------------------------------- // //# 連接:join // //# separat.join(xxx) // //# 錯誤用法:xxx.join("-") // //# print("-".join(test_list)) // System.Console.WriteLine(string.Join("-",test_array));//test_array是數組 ABCD-bcdef-cddbdf //# # ------------------------------------------------------------- // // //# # 頭尾判斷:startswith(以。。。開頭),endswith(以。。。結尾) // //# # test_str.startswith(以。。。開頭) // var start_end_str="http://www.baidu.net"; // //# print(start_end_str.startswith("https://") or start_end_str.startswith("http://")) // System.Console.WriteLine(start_end_str.StartsWith("https://")||start_end_str.StartsWith("http://")); // //# print(start_end_str.endswith(".com")) // System.Console.WriteLine(start_end_str.EndsWith(".com")); // //# # ------------------------------------------------------------- // // // //# # 大小寫系:lower(字符串轉換為小寫),upper(字符串轉換為大寫),title(單詞首字母大寫),capitalize(第一個字符大寫,其他變小寫) // //# print(test_str) // //# print(test_str.upper())#ABCDABCDEFACDDBDF // System.Console.WriteLine(test_str.ToUpper()); // //# print(test_str.lower())#abcdabcdefacddbdf // System.Console.WriteLine(test_str.ToLower()); // //# print(test_str.capitalize())#第一個字符大寫,其他變小寫 // // // //# # ------------------------------------------------------------- // // // //# # 格式系列:lstrip(去除左邊空格),rstrip(去除右邊空格),strip(去除兩邊空格),ljust,rjust,center // var strip_str=" I Have a Dream "; // //# print(strip_str.strip()+"|")#我加 | 是為了看清後面空格,沒有別的用處 // System.Console.WriteLine(strip_str.Trim()+"|"); // //# print(strip_str.lstrip()+"|") // System.Console.WriteLine(strip_str.TrimStart()+"|"); // //# print(strip_str.rstrip()+"|") // System.Console.WriteLine(strip_str.TrimEnd()+"|"); //# #這個就是格式化輸出,就不講了 //# print(test_str.ljust(50)) //# print(test_str.rjust(50)) //# print(test_str.center(50)) //# # ------------------------------------------------------------- // // //# 驗證系列:isalpha(是否是純字母),isalnum(是否是數字|字母),isdigit(是否是純數字),isspace(是否是純空格) // // // //# test_str2="Abcd123" // //# test_str3="123456" // var test_str4=" \t"; // var test_str5=" \t \n "; //#isspace() ==>true // // string.IsNullOrEmpty 和 string.IsNullOrWhiteSpace 是系統自帶的,其他的你需要自己封裝一個擴展類 // System.Console.WriteLine(string.IsNullOrEmpty(test_str4)); //false // System.Console.WriteLine(string.IsNullOrWhiteSpace(test_str4));//true // System.Console.WriteLine(string.IsNullOrEmpty(test_str5));//false // System.Console.WriteLine(string.IsNullOrWhiteSpace(test_str5));//true // //# 一張圖搞定,其他的自己去試一試吧 // //# test_str.isalpha() // //# test_str.isalnum() // //# test_str.isdigit() // //# test_str.isspace() #endregion // Console.Read(); } }}View Code 

簡單封裝:

using System;using System.Collections.Generic;using System.Linq;using System.Text.RegularExpressions;public static partial class ValidationHelper{ #region 常用驗證 #region 集合系列 ///  /// 判斷集合是否有數據 ///  ///  ///  ///  public static bool ExistsData(this IEnumerable list) { bool b = false; if (list != null && list.Count() > 0) { b = true; } return b; }  #endregion #region Null判斷系列 ///  /// 判斷是否為空或Null ///  ///  ///  public static bool IsNullOrWhiteSpace(this string objStr) { if (string.IsNullOrWhiteSpace(objStr)) { return true; } else { return false; } } ///  /// 判斷類型是否為可空類型 ///  ///  ///  public static bool IsNullableType(Type theType) { return (theType.IsGenericType && theType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))); } #endregion #region 數字字符串檢查 ///  /// 是否數字字符串(包括小數) ///  /// 輸入字符串 ///  public static bool IsNumber(this string objStr) { try { return Regex.IsMatch(objStr, @"^\d+(\.\d+)?$"); } catch { return false; } } ///  /// 是否是浮點數 ///  /// 輸入字符串 ///  public static bool IsDecimal(this string objStr) { try { return Regex.IsMatch(objStr, @"^(-?\d+)(\.\d+)?$"); } catch { return false; } } #endregion #endregion #region 業務常用 #region 中文檢測 ///  /// 檢測是否有中文字符 ///  ///  ///  public static bool IsZhCN(this string objStr) { try { return Regex.IsMatch(objStr, "[\\u4e00-\\u9fa5]"); } catch { return false; } } #endregion #region 郵箱驗證 ///  /// 判斷郵箱地址是否正確 ///  ///  ///  public static bool IsEmail(this string objStr) { try { return Regex.IsMatch(objStr, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"); } catch { return false; } } #endregion #region IP系列驗證 ///  /// 是否為ip ///  ///  ///  public static bool IsIP(this string objStr) { return Regex.IsMatch(objStr, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$"); } ///  
/// 判斷輸入的字符串是否是表示一個IP地址 /// /// 被比較的字符串 /// 是IP地址則為True public static bool IsIPv4(this string objStr) { string[] IPs = objStr.Split('.'); for (int i = 0; i < IPs.Length; i++) { if (!Regex.IsMatch(IPs[i], @"^\d+$")) { return false; } if (Convert.ToUInt16(IPs[i]) > 255) { return false; } } return true; } /// /// 判斷輸入的字符串是否是合法的IPV6 地址 /// /// /// public static bool IsIPV6(string input) { string temp = input; string[] strs = temp.Split(':'); if (strs.Length > 8) { return false; } int count = input.GetStrCount("::"); if (count > 1) { return false; } else if (count == 0) { return Regex.IsMatch(input, @"^([\da-f]{1,4}:){7}[\da-f]{1,4}$"); } else { return Regex.IsMatch(input, @"^([\da-f]{1,4}:){0,5}::([\da-f]{1,4}:){0,5}[\da-f]{1,4}$"); } } #endregion #region 網址系列驗證 /// /// 驗證網址是否正確(http:或者https:)【後期添加 // 的情況】 /// /// 地址 /// public static bool IsWebUrl(this string objStr) { try { return Regex.IsMatch(objStr, @"http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?|https://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"); } catch { return false; } } /// /// 判斷輸入的字符串是否是一個超鏈接 /// /// /// public static bool IsURL(this string objStr) { string pattern = @"^[a-zA-Z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$"; return Regex.IsMatch(objStr, pattern); } #endregion #region 郵政編碼驗證 /// /// 驗證郵政編碼是否正確 /// /// 輸入字符串 /// public static bool IsZipCode(this string objStr) { try { return Regex.IsMatch(objStr, @"\d{6}"); } catch { return false; } } #endregion #region 電話+手機驗證 /// /// 驗證手機號是否正確 /// /// 手機號 /// public static bool IsMobile(this string objStr) { try { return Regex.IsMatch(objStr, @"^13[0-9]{9}|15[012356789][0-9]{8}|18[0123456789][0-9]{8}|147[0-9]{8}$"); } catch { return false; } } /// /// 匹配3位或4位區號的電話號碼,其中區號可以用小括號括起來,也可以不用,區號與本地號間可以用連字號或空格間隔,也可以沒有間隔 /// /// /// public static bool IsPhone(this string objStr) { try { return Regex.IsMatch(objStr, "^\\(0\\d{2}\\)[- ]?\\d{8}$|^0\\d{2}[- ]?\\d{8}$|^\\(0\\d{3}\\)[- ]?\\d{7}$|^0\\d{3}[- ]?\\d{7}$"); } catch { return false; } } #endregion #region 字母或數字驗證 /// /// 是否只是字母或數字 ///
/// /// public static bool IsAbcOr123(this string objStr) { try { return Regex.IsMatch(objStr, @"^[0-9a-zA-Z\$]+$"); } catch { return false; } } #endregion #endregion}View Code

說這麼多基本上差不多完了,下次列表+字典+元組就一起講了啊~

原文:


分享到:


相關文章: