如何在字符串中搜索字符"
。
答案 0 :(得分:3)
您可以使用string :: find()函数。访问here了解更多信息
#include <string>
using namespace std;
int main ()
{
string str ("foo\"bar");
string str2 ("\"");
size_t found;
//you may want to do str.find('"') if you are only looking for one char.
found=str.find(str2);
}
逃避“定义的字符串中的字符”非常重要。
答案 1 :(得分:2)
在未排序字符串中查找字符的最佳方法是线性搜索:
for each index in the string:
if the character at that index matches the search criteria:
report the current index
report not found
当然,还有一个功能:std::string::find,如果找不到该字符,将返回std::string::npos;否则,该函数将返回首次找到该字符的索引。还有std::string::find_first_of,std::string::find_last_of和他们的“not_of”变体之类的变体。
答案 2 :(得分:2)
答案 3 :(得分:2)
这是一个简单的解决方案:
#include <string.h>
using namespace std;
int findChar(char c, string myString)
{
pos = myString.find(c); // Find position in the string (to access myString[pos])
return int(pos);
}
答案 4 :(得分:0)
这是对C ++中的库没有依赖性的解决方案
char * foo = "abcdefg";
char cf = 'e'; // Char to find
int f = 0; while (*(foo + f++) != cf); // f is 5