繁体   English   中英

有关C ++字符串的问题

[英]Questions regarding C++ string

phrase.erase(remove_if (phrase.begin(), phrase.end(), ::isdigit), phrase.end());

在上面的代码中,即使using namespace std ,为什么也必须使用::

#include "Palindrome.h"
#include <iostream>
#include <string.h>
#include <algorithm>

using namespace std;

Palindrome::Palindrome (string Phrase){
    phrase=Phrase;
}

void Palindrome::removeNonLetters()
{
    phrase.erase(remove_if (phrase.begin(), phrase.end(), ::isdigit), phrase.end());

    phrase.erase(remove_if (phrase.begin(), phrase.end(), ::ispunct), phrase.end());

    phrase.erase(remove_if (phrase.begin(), phrase.end(), ::isspace), phrase.end());
}

void Palindrome::lowerCase()
{
    for (int i=0; i<phrase.length(); i++)
    {
        phrase[i] = tolower(phrase[i]); 
    }
}

bool Palindrome::isPalindrome()
{
    int length=phrase.length(); 
    int a=0;    
    for (int i=0;i<length/2;i++)
    { 
        if(phrase[i] != phrase[length-a-1])
        {
            return false;
            break;
        }
        a++;
    }
    return true;
}

上面的代码是检查字符串是否是回文。 我不明白为什么我需要使用第一部分

Palindrome::Palindrome (string Phrase){
    phrase=Phrase;
}

如果我删除了上面的部分,我将总是“是”。

主要的测试代码是

if(test.Palindrome::isPalindrome() == 1){
    cout<<"Yes"<<endl;
}
else {
    cout<<"No"<<endl;
}

还有一个问题。 我尝试更改上述代码的小写字母,但出现错误。 有人知道会发生什么吗? 新代码来自https://www.geeksforgeeks.org/conversion-whole-string-uppercase-lowercase-using-stl-c/

之前

 void Palindrome::lowerCase()
{
    for (int i=0; i<phrase.length(); i++)
    {
        phrase[i] = tolower(phrase[i]); 
    }
}

void Palindrome::lowerCase(){

transform(phrase.begin(), phrase.end(), phrase.begin, ::tolower);

}

谁能向我解释? 非常感谢!

有多个isdigitispunctisspace函数-在<ctype.h>头文件的全局命名空间中,在<cctype><clocale>头文件的std命名空间中有多个。 ::前缀表示您要使用全局名称空间中的那些。

为了使用std::string类,您需要使用<string>而不是<string.h>

假设testPalindrome对象,则test.Palindrome::isPalindrome()应该只是test.isPalindrome()

如果省略Palindrome构造函数,则phrase成员保持空白,并且isPalindrome()实现对空白phraselength为0)返回true ,因为for循环无需检查。 从技术上讲这是正确的-空字符串是回文。

::表示您正在使用isdigit ,而其他人则使用全局命名空间。 isdigit是其他头文件的一部分,例如<ctype.h>

暂无
暂无

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

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