有关字符串C++问题

Questions regarding C++ string

本文关键字:问题 C++ 字符串      更新时间:2023-10-16
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命名空间中。 在它们前面加上::表示您希望使用全局命名空间中的那些。

您需要使用<string>而不是<string.h>才能使用std::string类。

假设test是一个Palindrome对象,那么test.Palindrome::isPalindrome()应该只是test.isPalindrome()

如果省略Palindrome构造函数,则phrase成员将保持空白,并且isPalindrome()实现返回空白phrasetrue(length为 0),因为for循环无需检查任何内容。 这在技术上是正确的 - 空白字符串是一个回文。

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