C 字串string的常用函式

2021-09-09 09:24:36 字數 2811 閱讀 9188

#include

#include

#include

using namespace std;

intmain()

輸出結果:

上面所描述的是將乙個字串裡面某個區間內的大寫字母轉換為小寫字母(小寫字母轉換為大寫字母),然後儲存到另乙個空字串裡面;如:

transform

(str1.

begin()

,str1.

end(

),str2.

begin()

,::tolower)

;

前面兩個引數是指從str1的頭部一直到str1的尾部,而第三個引數是指儲存在str2中,第四個引數表示的就是你想要把大寫變成小寫::tolower還是把小寫變成大寫::toupper;

這時你應該能想到,能否直接在字串本身儲存變換後的字串,答案是可以的;將第三個引數修改為字串本身即可,如:

transform

(str1.

begin()

,str1.

end(

),str1.

begin()

,::tolower)

;

這就是直接在字串本身修改了;

#include

#include

#include

using namespace std;

intmain()

輸出結果:

如上面的**所示,只需要把某個字元傳到isalpha()函式裡面,函式就會返回01

相類似的函式有很多,標頭檔案都是如:

isalpha():判斷是否為字母;

islower():判斷是否為小寫字母;

isupper():判斷是否為大寫字母;

isalnum():判斷是否為字母或數字;

isspace():判斷是否為空格;

#include

#include

using namespace std;

intmain()

輸出結果:

substr()函式有兩個引數,第乙個引數指的是你要擷取的子串的第乙個元素在源字串的下標,第二個引數就是你要擷取的字串的長度;要注意的是,str1經過擷取後,str1是不會發生變化的;

#include

#include

using namespace std;

intmain()

輸出結果:

要注意的是,這裡面的str並不能是string型別的字串,而要是字元陣列;

#include

#include

using namespace std;

intmain()

輸出結果:

erase()函式的兩個引數,第乙個引數是指要刪除的那一段的第乙個字元在源字串的下標,第二個引數是要刪除的那一段的長度;

#include

#include

using namespace std;

intmain()

輸出結果:

在使用compare()函式時,如果str1str2相等的話,函式返回0,如果str1>str2則返回1,如果str1<str2,則返回-1;比較字串的方法就是按照字元的ascii碼值來比較的;

#include

#include

using namespace std;

intmain()

輸出結果:

如果查詢的物件在字串中有多個,那麼函式返回的僅僅是第乙個的位置;

C 常用的string字串截斷函式

c 中經常會用到標準庫函式庫 stl 的string字串類,跟其他語言的字串類相比有所缺陷。這裡就分享下我經常用到的兩個字串截斷函式 include include include include using namespace std 根據字元切分string,相容最前最後存在字元 void cu...

String字串函式

1.定義乙個字串 var str aheloworld 2.獲取字串長度 string.length var str aheloworld console.log str.length 3.返回指定位置下標的字元 string.charat var str sajdhjhasdko var str1...

PHP中常用的String字串函式

1.htmlspecialchars 函式把預定義的字元轉換為 html 實體。2.trim str,removestr 移除字串兩側的字元,str是要操作的字串,removestr是想要 移除的字元 ltrim和rtrim分別是移除字串左邊的指定字元和移除字串右邊的指定字元,語法和trim相同 3...