C string類如何判斷字串為空

2022-07-01 12:21:08 字數 672 閱讀 4270

string類是c++stl類之一,有很豐富的介面,判斷string為空是經常用到的操作。

string類為空,實際也就是元素為0個。 可以按照如下方式判斷:

1、string類有自己的成員函式empty, 可以用來判斷是否為空:

string str;

if(str.empty())//成立則為空

...

2、判斷字串長度。如果長度為0,則為空:

string str;

if(str.size()==0)//成立則為空

...

3、與空串比較,如果相等則為空:

string str;

if(str=="")//成立則為空

...

幾種方法中,empty函式是效率最高也是最常用的一種。

注意:

不能使用str==null來判斷,null一般只拿和指標做比較或者賦給指標,string是類,傳參進函式時str呼叫預設的建構函式已經初始化了,並且str都已經是物件了,它不可能為null,也不能和null比較。

更多參考

C string類如何判斷字串為空

string類是c stl類之一,有很豐富的介面。string類為空,實際也就是元素為0個。可以按照如下方式判斷 string str if str.empty 成立則為空 string str if str.size 0 成立則為空 string str if str 成立則為空 但不能使用str...

c string類字串查詢

1 find 函式 find 函式用於在 string 字串中查詢子字串出現的位置,它其中的兩種原型為 size t find const string str,size t pos 0 const size t find const char s,size t pos 0 const 第乙個引數為...

C string類中的字串查詢

c string類中的字串查詢 類string提供了大量查詢功能和搜尋功能,其中比較常用的查詢和搜尋函式是find 函式 find first not of 函式 find first of 函式 find last not of 函式 find last of 函式 rfind 等。find 函式...