繁体   English   中英

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

[英]Find the index of a special character in string in C++

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

你可以使用std::strchr

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

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

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

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

使用std::string您还可以在其上找到要查找的字符的方法。

strchrstd::string::find ,具体取决于字符串的类型?

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 
#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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM