我的问题:如何判断字符串中的单词是否包含数字?
我需要做的:编写一个程序,读取一行文本并输出该行,其中所有整数中的所有数字都替换为“x”。
例如:
My userID is john17 and my 4 digit pin is 1234 which is secret.
应该变成
My userID is john17 and my x digit pin is xxxx which is secret.
注意 john17 中的数字如何不受影响。
我目前的代码:
#include <iostream>
using namespace std;
int main()
{
string str;
int i;
cout << "Enter a line of text: ";
getline(cin, str);
for (i = 0; i <= str.length(); i++)
{
if (str[i] >= '0' && str[i] <= '9')
{
str.at(i) = 'x';
}
}
cout << "Edited text: " << str << endl;
}
最佳答案
您可以使用很多方法。以下是其中一些:
1 - 通用算法:
遍历字符串: 例如:
“我的用户 ID 是 john17,我的 4 位密码是 1234,这是保密的。”
当您在
space
字符后面找到一个数字并开始缓存该单词时,设置一个 bool 标志 (IsNumberOnly=true
)。请注意,该标志最初是false
。例如,您的示例中的第二个'1'
是紧跟在space
字符之后的数字。继续迭代,如果在到达另一个
space
之前找到一个非数字,则设置IsNumberOnly=false
,说完这个词。如果
IsNumberOnly=true
则打印'x'
(cashed 单词中的字符数)否则打印 cashed 单词,例如17John
.
请注意,这里 john17
完全不会受到影响。即使是 17john
也不会受到影响。
或
2 - 如果您想使用 The Library 和 C++11,那么您可以通过以下方式逐一阅读和测试单词:
std::all_of(str.begin(), str.end(), ::isdigit); // C++11
有关更多详细信息和示例:
http://en.cppreference.com/w/cpp/algorithm/all_any_none_of
或
3 - 这样的事情就可以了:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string str;
cout << "Enter a line of text: ";
getline(cin,str);
istringstream iss(str);
string word;
string finalStr="";
while(iss >> word) {
if(word.find_first_not_of( "0123456789" ) == string::npos)
{
for(int i=0; i<word.size(); i++)
{
finalStr+='x';
}
}
else
{
finalStr.append(word);
}
finalStr+=' ';
}
cout << "Edited text: " << finalStr << endl;
return 0;
}
这些只是一些例子。
希望对您有所帮助!
关于c++ - 如何知道字符串中的单词是否有数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29871180/