[英]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
命名空間中有多個。 用::
前綴表示您要使用全局名稱空間中的那些。
為了使用std::string
類,您需要使用<string>
而不是<string.h>
。
假設test
是Palindrome
對象,則test.Palindrome::isPalindrome()
應該只是test.isPalindrome()
。
如果省略Palindrome
構造函數,則phrase
成員保持空白,並且isPalindrome()
實現對空白phrase
( length
為0)返回true
,因為for
循環無需檢查。 從技術上講這是正確的-空字符串是回文。
::
表示您正在使用isdigit
,而其他人則使用全局命名空間。 isdigit
是其他頭文件的一部分,例如<ctype.h>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.