有关字符串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);
}
谁能向我解释一下?非常感谢!
有多个isdigit
、ispunct
和isspace
函数 - 一个在<ctype.h>
标头的全局命名空间中,几个在<cctype>
和<clocale>
标头的std
命名空间中。 在它们前面加上::
表示您希望使用全局命名空间中的那些。
您需要使用<string>
而不是<string.h>
才能使用std::string
类。
假设test
是一个Palindrome
对象,那么test.Palindrome::isPalindrome()
应该只是test.isPalindrome()
。
如果省略Palindrome
构造函数,则phrase
成员将保持空白,并且isPalindrome()
实现返回空白phrase
的true
(length
为 0),因为for
循环无需检查任何内容。 这在技术上是正确的 - 空白字符串是一个回文。
::
表示您正在使用全局命名空间中的isdigit
和其他内容。isdigit
是其他头文件的一部分,例如<ctype.h>
。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题