C 字串string操作

2021-10-05 05:42:27 字數 2655 閱讀 9935

相比於c語言而言,c++提供了太多的寫好了的型別和方法,其中string型別就是用起來特別方便的一種。那麼問題來了,既然有c語言的char型,為什麼還要學習string型別呢?我碰到過的也是最主要的乙個原因就是string型別更節省空間,用多少開多少,而char型別的陣列就不是了,必須開最大值。其次還有乙個重要的原因就是c++中的map容器等不支援char型陣列的,只能寫mapmp這樣。所以,扯了這麼多,就來跟我看看string型別常用的技能吧。

首先要使用string資料型別,需要引入標頭檔案 #include,注意不是string.h標頭檔案。

1.string型別的宣告: 

string s;

2.string型別的初始化:    

string s="abcd";   或者   string s="a  b   cd";

這兩種分別是不帶空格和帶空格的初始化,是都可以的。

3.string型別的讀入:

cin>>s;             //不能讀入空格,以空格、製表符、回車符作為結束標誌

getline(cin,s);   //可以讀入空格和製表符,以回車符作為結束標誌

4.求string型別的長度:

int len=s.size();    或者     int len=s.length();

兩種方法是等價的

5.求string型別下標為i的字元:

s[i]        或        char c=s.at(i)

6.查詢t是否為s的子串:

s.find(t);

如果t是s的子串則返回首次匹配的位置,否則返回 string::npos 或 -1

7.字元陣列轉string型別:

s=str;

str為char陣列,s為string型別

8.string型別轉字元陣列:

strcpy(str,s.c_str());

需要引用string.h標頭檔案

9.兩個string比較大小:

if(s1相等時返回0;s1>s2時返回1,s1字串可以和型別相同的字串相比較,也可以和具有同樣字元型別的陣列比較。

basic_string 類模板既提供了  >、<、==、>=、<=、!= 等比較運算子,還提供了 compare() 函式,其中 compare() 函式支援多引數處理,支援用索引值和長度定位子串進行比較。該函式返回乙個整數來表示比較結果。如果相比較的兩個子串相同,compare() 函式返回 0,否則返回非零值。

類 basic_string 的成員函式 compare() 的原型如下:

int compare (const basic_string& s) const;

int compare (const ch* p) const;

int compare (size_type pos, size_type n, const basic_string& s) const;

int compare (size_type pos, size_type n, const basic_string& s,size_type pos2, size_type n2) const;

int compare (size_type pos, size_type n, const ch* p, size_type = npos) const;

如果在使用 compare() 函式時,引數**現了位置和大小,比較時只能用指定的子串。例如:

s.compare

程式的執行結果為:

m = 1, n = -1, p = -1, q = 0

由此可知,string 類的比較 compare() 函式使用非常方便,而且能區分字母的大小寫。建議讀者多使用此函式。

string 類的常見運算子包括 >、<、==、>=、<=、!=。其意義分別為"大於"、"小於"、"等於"、"大於等於"、"小於等於"、"不等於"。

比較運算子使用起來非常方便,此處不再介紹其函式原型,讀者直接使用即可。下面以例 2 進行說明。

【例 2】

#include 

#include

using namespace std;

void trueo***lse (int x)

int main ()

程式執行結果為:

s1= def

cp1 = abc

cp2 = def

cp3 = defg

cp4 = def

s1 <= cp1 returned false

s1 <= cp2 returned true

s1 <= cp3 returned true

cp1 <= s1 returned true

cp2 <= s1 returned true

cp4 <= s1 returned false

由上述內容可知,使用比較運算子可以非常容易地實現字串的大小比較。在使用時比較運算子時,讀者應注意,對於參加比較的兩個字串,任乙個字串均不能為null,否則程式會異常退出。

11對string型別陣列排序

string s[100];

sort(s,s+n,cmp);

int cmp(string a,string b)

其中sort函式為c++ stl中提供的快速排序函式。

------------------

String字串操作

char chars string s new string chars int len s.length 字串長度 system.out.println chars ab system.out.println s abc system.out.println len 3 char ch zhang...

c 字串string的操作

1.字串的宣告 include include include using namespace std int main else cout 方法2,string npos可強制轉換為 1 n int local local static cast s.find make 20 if local 1...

c 字串string的操作

1 include 2 include 3 include 45 using namespace std 67 intmain 879 else 82 83 cout 方法2,string npos可強制轉換為 1 n 84int local 85 local static cast s.find ...