C++ 在C++中查找字符串中特殊字符的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4376359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:15:56  来源:igfitidea点击:

Find the index of a special character in string in C++

c++stringvisual-studio-2010visual-c++

提问by rain

I wanna know if there is any standard function in visual stodio 2010, C++, which takes a character, and returns the index of it in special string, if it is exist in the string. Tnx

我想知道visual stodio 2010,C++中是否有任何标准函数,它接受一个字符,并在特殊字符串中返回它的索引,如果它存在于字符串中。Tnx

采纳答案by Pablo Santa Cruz

You can use std::strchr.

您可以使用std::strchr.

If you have a Clike string:

如果你有一个类似C 的字符串:

const char *s = "hello, weird + char.";
strchr(s, '+'); // will return 13, which is '+' position within string

If you have a std::stringinstance:

如果您有一个std::string实例:

std::string s = "hello, weird + char.";
strchr(s.c_str(), '+'); // 13!

With a std::stringyou can also a method on it to find the character you are looking for.

使用 astd::string您还可以使用一种方法来查找您要查找的字符。

回答by NPE

strchror std::string::find, depending on the type of string?

strchr或者std::string::find,取决于字符串的类型?

回答by DanS

strchr() returns a pointer to the character in the string.

strchr() 返回指向字符串中字符的指针。

const char *s = "hello, weird + char."; 
char *pc = strchr(s, '+'); // returns a pointer to '+' in the string
int idx = pc - s; // idx 13, which is '+' position within string 

回答by Jo?o Víctor

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main() {
    string text = "this is a sample string";
    string target = "sample";

    int idx = text.find(target);

    if (idx!=string::npos) {
        cout << "find at index: " << idx << endl;
    } else {
        cout << "not found" << endl;
    }

    return 0;
}