【发布时间】:2015-04-16 07:05:46
【问题描述】:
我有一串很多字母
string path = "cxzaserds";
还有一个目标词
string word = "cars";
在我的函数match() 中,如果在路径中(按顺序)找到来自word 的字符,我想返回true,在这种情况下,它将返回true('c' 出现在'a' 之前'在path 字符串中,r' 位于 's' 之前)。
我正在尝试使用strtok() 逐个查找每个字符,分隔符是当前索引的字母。
我的进步:
bool match (string path, string word)
{
char * cstr = new char [path.length()+1]; //workaround for strtok on string
std::strcpy (cstr, path.c_str());
char *p;
for (int i = 0 ; i < path.length(); i++)
{
//error here, "invalid conversion from 'char' to 'const char*'
p = strtok (cstr, word[i]);
if (p != NULL) //if strtok found word[i]
continue;
else return false; //was NULL, word not found
}
return true; //made it through, return true
}
在 C++ 页面的分隔符下,它说:
这些可能与一个调用不同。
http://www.cplusplus.com/reference/cstring/strtok/
当 strtok 返回非 null 时,我可以做些什么来更改分隔符? 或者完全是另一种(更简单的)解决方案?
【问题讨论】:
-
strtok的第二个参数是char*,而不是char,word[i]是char。这是一个分隔符列表,而不是单个。我会怎么做?放弃strotk以支持更多 C++ 风格。 Related post.