2010-02-27 133 views
6

我有一个很大的空间开出的字符串。如果我想找出不是空格的第一个字符的位置,我该怎么做?如何找到在C中第一个字符的字符串++

+2

你的字符串是什么编码?如果它是ASCII,那么只有4个空白字符,而Vlad的find_first_not_of解决方案很好。 ASCII或拉丁语1字符串可能涵盖教学练习。如果您的字符串是UTF-8或宽字符std :: wstring(因为它可能位于真实应用程序中),则可以询问另一个问题。 – 2010-02-27 10:14:54

+0

是,在这些情况下,人们将能够在同一职位(可以使用BLL的'的boost :: labda ::绑定(isspace为,_1,my_locale)的botom使用'find_if'解决方案',以配合特定的语言环境' my_locale'改为'isspace'而不是使用默认值)。 – vladr 2010-03-04 01:06:21

回答

15

std::string::find_first_not_of

为了找到位置(索引)的第一个非空格字符的

str.find_first_not_of(' '); 

为了找到第一个非空白字符的位置(索引):

str.find_first_not_of(" \t\r\n"); 

如果str为空或完全由空白组成,它将返回str.npos

您可以使用find_first_not_of修剪违规前导空格:

str.erase(0, str.find_first_not_of(" \t\r\n")); 

如果你不想硬编码的字符数为空白(如使用区域),你仍然可以使用的isspacefind_if或多或少以最初由sbi建议的方式,但注意否定isspace,例如:

string::iterator it_first_nonspace = find_if(str.begin(), str.end(), not1(isspace)); 
// e.g. number of blank characters to skip 
size_t chars_to_skip = it_first_nonspace - str.begin(); 
// e.g. trim leading blanks 
str.erase(str.begin(), it_first_nonspace); 
5

我只有一个问题:你真的需要额外的空白?

我将调用的Boost.String有力量;)

std::string str1 = "  hello world!  "; 
std::string str2 = boost::trim_left_copy(str1); // str2 == "hello world!  " 

有很多操作(findtrimreplace,...),以及谓词可以在这个库,只要你需要string操作没有提供开箱即用,请点击这里。此外,算法每次都有几个变体(通常不区分大小写和复制)。

相关问题