2010-02-26 63 views
3

我想檢查我的字符串中是否有兩個連續空格。什麼是最容易找到的方法?如何查找字符串中兩個連續空格的位置

+0

's.find(「 「)'也許? – falstro 2010-02-26 13:11:54

+1

我同意@Jon Winstanley ...太空你的意思是ASCII字符32(0x20),還是你的意思是一般的空白? – Bill 2010-02-26 13:31:52

+0

我認爲這只是空白。字符串不會將空白和空格視爲同一事物嗎? – neuromancer 2010-02-27 07:54:00

回答

6

使用std::stringfind()方法。它返回的特殊常量std::string::npos如果值沒有被發現,所以這是很容易檢查:

if (myString.find(" ") != std::string::npos) 
{ 
    cerr << "double spaces found!"; 
} 
0
Make search for " " in the string. 
+2

對不起,但是什麼? – moatPylon 2010-02-26 13:13:24

+2

哦,你對英語++不熟悉? – 2010-02-26 14:28:41

0

使用C:

#include <cstring> 
... 
addr = strstr (str, " "); 
... 
+2

如果你打算使用'strstr',你應該使用'str.c_str()',因爲它需要'char *'。 – Javier 2010-02-26 13:14:44

1
#include <string> 

bool are_there_two_spaces(const std::string& s) { 
    if (s.find(" ") != std::string::npos) { 
     return true; 
    } else { 
     return false; 
    } 
} 
+2

爲什麼顯式返回布爾值?如果你想有一個函數,可以考慮直接返回比較結果。它的定義是布爾值。 – unwind 2010-02-26 13:25:34

+0

'return(s.find(「」)!= std :: string :: npos);'應該這樣做。不過,我會猜想這會被優化。 – legends2k 2010-02-26 13:33:46

+0

@unwind:我知道,但由於提問者不知道這個函數,所以我儘可能清楚地寫出例子。 – Javier 2010-02-26 14:40:27

0
string s = "foo bar"; 
int i = s.find(" "); 
if(i != string::npos) 
    cout << "Found at: " << i << endl; 
相關問題