我有一个词是C++如何获得字符串/字符的话
AD#安道尔
有几个问题2之间:
如何检查AD 安道尔存在
?是通配符,它可以是逗号或十六进制或美元符号或其他值
然后确认AD?安道尔存在后,我如何获得值?
感谢, 陈
我有一个词是C++如何获得字符串/字符的话
AD#安道尔
有几个问题2之间:
如何检查AD 安道尔存在
?是通配符,它可以是逗号或十六进制或美元符号或其他值
然后确认AD?安道尔存在后,我如何获得值?
感谢, 陈
问题可以通常与正则表达式匹配来解决。但是,对于您提出的具体问题,这会工作:
std::string input = getinput();
char at2 = input[2];
input[2] = '#';
if (input == "AD#Andorra") {
// match, and char of interest is in at2;
} else {
// doesn't match
}
如果?
应该代表一个字符串也,那么你可以做这样的事情:
bool find_inbetween (std::string input,
std::string &output,
const std::string front = "AD",
const std::string back = "Andorra") {
if ((input.size() < front.size() + back.size())
|| (input.compare(0, front.size(), front) != 0)
|| (input.compare(input.size()-back.size(), back.size(), back) != 0)) {
return false;
}
output = input.substr(front.size(), input.size()-front.size()-back.size());
return true;
}
假设你的角色总是开始于第3位! 使用字符串功能substr
:
your_string.substr(your_string,2,1)
我不会使用'substr'来检查一个字符串中的一个(固定)位置。 – 2012-08-06 11:06:43
如果您正在使用C++ 11,我建议你在你的字符串中使用正则表达式而不是直接搜索。
如果你在C++ 11 /使用Boost(我强烈推荐!)使用正则表达式。一旦你获得了一定程度的理解,所有的文本处理变得简单易懂!
#include <regex> // or #include <boost/regex>
//! \return A separating character or 0, if str does not match the pattern
char getSeparator(const char* str)
{
using namespace std; // change to "boost" if not on C++11
static const regex re("^AD(.)Andorra$");
cmatch match;
if (regex_match(str, match, re))
{
return *(match[1].first);
}
return 0;
}
调试的噩梦!请,请不要使用单行如果&返回。 – gwiazdorrr 2012-08-06 15:56:05
@gwiazdorrr:当然,问候 – jxh 2012-08-06 15:57:31