C ++替换字符数组中的单词

时间:2016-10-30 22:04:38

标签: c++ arrays

我正在解决一个问题,我需要让用户输入一条消息然后替换工作"请参阅"与" c"。我想阅读数组消息[200],然后将其分解为单个单词。我尝试了一个for循环,但是当我将它结合起来时,它只是添加了相关的单词。我只使用字符数组,没有字符串。

const int MAX_SIZE = 200;

int main(){

    char message[MAX_SIZE]; //message array the user will enter
    int length;     // count of message lenght
    int counter, i, j;      //counters for loops
    char updateMessage[MAX_SIZE];   //message after txt update

    //prompt user to
    cout << "Please type a sentence" << endl;
    cin.get(message, MAX_SIZE, '\n');
    cin.ignore(100, '\n');

    length = strlen(message);
    //Lower all characters
    for( i = 0; i < length; ++i)
    {
        message[i] = tolower(message[i]);


    //echo back sentence
    cout << "You typed: " << message << endl;
    cout << "Your message length is " << length << endl;

    for( counter = 0; counter <= length; ++counter)
    {

            updateMessage[counter] = message[counter];

            if(isspace(message[counter]) || message[counter] == '\0')
            {
                    cout << "Space Found" << endl;
                    cout << updateMessage << endl;
                    cout << updateMessage << " ** " << endl;

            }
    }
return 0;
}

找到每个空格后,我想只输出一个作品。

1 个答案:

答案 0 :(得分:1)

您应该尝试学习一些现代C ++和标准库功能,因此您最终不会在C ++中编写C代码。作为一个例子,这就是C ++ 14程序如何利用库中的标准算法来完成10-15行代码的工作:

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

int main()
{
    using namespace std::string_literals;

    std::istringstream input("Hello I see you, now you see me");
    std::string str;

    // get the input from the stream (use std::cin if you read from console)
    std::getline(input, str);

    // tokenize
    std::vector<std::string> words;
    std::istringstream ss(str);
    for(std::string word ; ss >> word; words.push_back(word));

    // replace
    std::replace(words.begin(), words.end(), "see"s, "c"s);

    // flatten back to a string from the tokens
    str.clear();
    for(auto& elem: words)
    {
        str += elem + ' ';
    }

    // display the final string
    std::cout << str;
}

Live on Coliru

这不是最有效的方法,因为您可以在适当的位置执行替换,但代码是清晰的,如果您不需要保存每一个CPU周期,它就能很好地执行。

以下是避免std::vector并执行替换的解决方案:

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

int main()
{
    std::istringstream input("Hello I see you, now you see me");
    std::string str;

    // get the input from the stream (use std::cin if you read from console)
    std::getline(input, str);

    // tokenize and replace in place
    std::istringstream ss(str);
    std::string word;
    str.clear();
    while (ss >> word)
    {
        if (word == "see")
            str += std::string("c") + ' ';
        else
            str += word + ' ';
    }

    // display the final string
    std::cout << str;
}

Live on Coliru