2015-05-04 81 views
-6

我知道方法strchr,它在字符数组中找到第一次出现的任何字符。但是如何查找字符串中第一次出现的任何字符?第一次出现字符串中的字符

更具体地说,我想任何方法来做到这一点 - >

 [email protected]/contest.icpc/12 

上搜索@它应该给10和上搜索/它应该给25和38不会

+0

文档:http://en.cppreference.com/w/cpp/string/basic_string – Galik

+0

另请参见['std :: find'](http://en.cppreference.com/w/cpp/algorithm/找)。 – juanchopanza

回答

2

使用std::string::find(char c)

std::string a = "[email protected]/contest.icpc/12"; 
cout << a.find('.') << endl; //4 
cout << a.find('/') << endl; //24 
+0

是它的工作原理,但为什么当我将'/'更改为'\'时,它给了我错误。像“缺少终止字符”。 –

+2

@chotabheem如果你想知道,那就问这个问题。没有完全不同的一个。 – juanchopanza

+0

@juanchopanza不,我只想知道这一点..但不小心,我改变了斜杠,并注意到这个错误,这就是为什么我问。 –

0

你朋友是std::string::find_first_of()

std::string str("[email protected]/contest.icpc/12"); 
str.find_first_of("@"); // returns 10 
str.find_first_of("@/"); // returns 10 
str.find_first_of("/"); // returns 24 .. or so 
+0

为什么“@ /”我的意思是为什么反斜线 –

1

对于字符串你表现得到结果你在字符串中期望的字符'/'你应该使用表达式,它们低于

#include <iostream> 
#include <string> 

int main() 
{ 
    std::string s = "[email protected]/contest.icpc/12"; 

    std::cout << s.find('/') + 1 << std::endl; 
    std::cout << s.rfind('/') + 1 << std::endl; 
} 

写在程序中的程序输出是

25 
38 

考虑到该位置从0

开始否则,使用简单s.find()和/或s.rfind()

相关问题