2010-02-26 68 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; 
相关问题