c++ - 如何知道字符串中的单词是否有数字?

标签 c++

我的问题:如何判断字符串中的单词是否包含数字?

我需要做的:编写一个程序,读取一行文本并输出该行,其中所有整数中的所有数字都替换为“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 - 通用算法:

  1. 遍历字符串: 例如:“我的用户 ID 是 john17,我的 4 位密码是 1234,这是保密的。”

  2. 当您在 space 字符后面找到一个数字并开始缓存该单词时,设置一个 bool 标志 (IsNumberOnly=true)。请注意,该标志最初是 false。例如,您的示例中的第二个 '1' 是紧跟在 space 字符之后的数字。继续迭代,

  3. 如果在到达另一个 space 之前找到一个非数字,则设置 IsNumberOnly=false

  4. 说完这个词。如果 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/

相关文章:

c++ - 一种在 Qt 中管理 GUI 状态的 RAII

c++ - const 引用作为返回值如何在 C++ 中工作

c++ - 如何将类的某些 typedef 传递给模板

c++ - ZMQ Hello world 不起作用

c++ - 检索数组最干净的方法是什么?

C++ 模板函数优化失败

c++ - 为什么我会从 'int'到 'int*'的无效转换错误以及其他错误?

c++ - 无法创建表示安全或可标志的类

c++ - Emacs 中的 CC 模式赋值缩进

c++ - const 限定符从纯虚函数中消失