字符串中字符的首次出现

First occurence of a character in string

本文关键字:字符 字符串      更新时间:2023-10-16

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

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

john.smith@codeforces.ru/contest.icpc/12

在搜索@时,它应该给出 10,在搜索/时它应该给出 25 而不是 38。

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

std::string a = "john.smith@codeforces.ru/contest.icpc/12";
cout << a.find('.') << endl; //4
cout << a.find('/') << endl; //24

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

std::string str("john.smith@codeforces.ru/contest.icpc/12");
str.find_first_of("@");   // returns 10
str.find_first_of("@/");  // returns 10
str.find_first_of("/");   // returns 24 .. or so

对于您显示的字符串以获得您期望的字符串中的字符'/'结果,您应该使用下面程序中编写的表达式

#include <iostream>
#include <string>
int main()
{
std::string s = "john.smith@codeforces.ru/contest.icpc/12";
std::cout << s.find( '/' ) + 1  << std::endl;
std::cout << s.rfind( '/' ) + 1 << std::endl;
}   

程序输出为

25
38

考虑到仓位从 0 开始。

否则,只需使用s.find()和/或s.rfind()