Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/125.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;如何确定字符是否为单词中的第一个字符_C++ - Fatal编程技术网

C++ C++;如何确定字符是否为单词中的第一个字符

C++ C++;如何确定字符是否为单词中的第一个字符,c++,C++,这似乎应该很简单,但我似乎无法理解。我正在尝试编写一个函数,如果pos位置的字符是单词的第一个字符,该函数将返回true。在这种情况下,单词it定义为字母数字字符的任何字符串 以下是我的最新尝试: bool wordBeginsAt (const std::string& message, int pos) { string temp; int x; for (x=pos;isAlphanumeric(message[x]==true);x++) { t

这似乎应该很简单,但我似乎无法理解。我正在尝试编写一个函数,如果pos位置的字符是单词的第一个字符,该函数将返回true。在这种情况下,单词it定义为字母数字字符的任何字符串

以下是我的最新尝试:

bool wordBeginsAt (const std::string& message, int pos)
{
string temp;
int x;

    for (x=pos;isAlphanumeric(message[x]==true);x++)
    {
        temp[x] = message[x];
    }
        if (temp[pos]!=0)
        {
            return false;
        }

        else

        return true;

    }

 bool isAlphanumeric (char c)
{
     return (c >= 'A' && c <= 'Z')
     || (c >= 'a' && c <= 'z')
     || (c >= '0' && c <= '9');
}
bool wordBeginsAt(const std::string&message,int pos)
{
字符串温度;
int x;
对于(x=pos;isAlphanumeric(消息[x]==true);x++)
{
temp[x]=消息[x];
}
如果(温度[位置]!=0)
{
返回false;
}
其他的
返回true;
}
布尔isAlphanumeric(字符c)
{

return(c>='A'&&c='A'&&c='0'&&c根据您的定义,如果一个字符是字母数字的,那么它就是单词中的第一个字符,或者是字符串中的第一个字符,或者不是字母数字之前的字符。

那么,
是字母数字的(message[x]==true)
应该是
是字母数字的(message[x])==true
。但是您的代码还存在其他严重问题,例如写入超出
temp
的范围,并且循环逻辑完全错误,因此我认为最好重新开始

您需要做的是:

  • 检查字符是否为字母数字
  • 检查前一个字符是否不存在,或者是否没有前一个字符

不需要循环或变量。当
pos==0时,会出现第二个条件;如果您实际查看第一个字符,则不希望检查前一个字符。

如果您只是对位置
pos
感兴趣,为什么需要for循环?此外,
条件是alphanumeric(消息[x]==true)
看起来非常错误…
返回std::isalnum(message[pos])&&(pos==0 | | |!std::isalnum(message[pos-1]);
这似乎是个死胡同,我试图使用string.find(“”)和string.substr()现在…我不敢相信这是一个函数。John3136,我在使用for循环,因为我需要单词的位置,而不是整个字符串(字符串是一个段落),所以我尝试只将“单词”加载到临时字符串中,然后确定位置。必须运行一个小时左右,稍后再回来。谢谢,如果(isAlphanumeric)(message[pos])==true&&isAlphanumeric(message[pos-1])==false)成功了。@bryan确保为
pos==0时添加一个特例