用于争夺字符串短语的C ++程序

时间:2014-12-12 04:17:35

标签: c++ string

我正在编写一个程序来扰乱通过字符串读入的行。这些短语是:

交替的内角

毕达哥拉斯定理

直角三角形

基角

侧角侧

我想要扰乱每个单词,而不是整个短语,但要将每个短语保持在自己的行上(使用getline函数)。在每个短语之后,我输出与短语长度相对应的下划线,每个下划线之间留有空格,并且在与短语中单词的最后一个字母对应的下划线之后有一个双空格。

我必须单独加扰单词的功能:

void scramble (apstring w)

{
srand (time(NULL));
apstring orig = w;
for(int i=0; i<w.length(); i++)
{
    int newSpot=rand()%w.length();
    char temp = w[i];
    w[i]=w[newSpot];
    w[newSpot]=temp;
}
while (orig == w);

我想知道如何在

之后搜索每一行的空格
        getline(fin, phrase);

并通过加扰器单独发送每个单词,但输出输出短语中的正确间距,以及单词后面的正确数量的下划线。我想我需要将这些单词读成子串,并且可能需要清除#34; purge&#34;使用类似这样的字符串:

apstring purgeString(apstring word)
{
apstring newWord = "";
for (int i = 0; i < word.length(); i++)
{
    if (isalpha(word[i]))
        newWord += word[i];
}
return newWord;
}

任何帮助或建议都会非常感激,这一直困扰我一段时间。

2 个答案:

答案 0 :(得分:0)

好吧,也许是这样的(伪代码,因为我不熟悉apstring类):

apstring theWholeLine = "This is a sentence with some words";
apstring curWord;
for (int i=0; i<theWholeLine.length(); i++)
{
   char nextChar = theWholeLine[i];

   if (isalpha(nextChar)) 
   {
      curWord += nextChar;
   }
   else if (curWord.length() > 0)
   {
      cout << "Time to scramble the next word: " << curWord << endl;
      curWord = "";
   }
}
if (curWord.length() > 0)
{
   cout << "Time to scramble the final word: " << curWord << endl;
}

(您可以使用代码替换或扩充cout行,以进行适当的单词加扰和打印)

答案 1 :(得分:0)

您可以使用std::stringstream创建phrase并从中读取每个单词(以空格分隔),如下所示:

std::stringstream ss(phrase);
std::string word;
while (ss >> word) {
   // ... process word
}

我注意到你正在处理个别角色和C函数。虽然这不一定是一个糟糕的方法,但这是我如何退后一步让C ++ 11做繁重的工作:

#include <algorithm>
#include <random>
#include <string>
#include <sstream>

// obtain a seed from a random_device for random number generator
std::random_device seed;
std::minstd_rand rng(seed());

std::string shufflePhrase(const std::string& phrase)
{
    std::string shuffledPhrase;
    std::string underscores;
    std::stringstream ss(phrase);
    std::string word;

    while (ss >> word) {

        // <algorithm> has a nice shuffle function that works on all iterable types
        std::shuffle(word.begin(), word.end(), rng);
        shuffledPhrase += word + ' ';

        // Add an underscore and space for each letter in the word
        for (const auto& letter : word) {
            underscores += "_ ";
        }
        underscores += ' ';
    }

    // Combine our shuffled phrase and underscores. We strip off the last 2 spaces.
    return shuffledPhrase + underscores.substr(0, underscores.size()-2);
}

现在我们有了这个功能,我们可以这样称呼它:

std::cout << shufflePhrase("alternate interior angles") << std::endl;

可能的输出:

nateaerlt ietnorri nlages _ _ _ _ _ _ _ _ _  _ _ _ _ _ _ _ _  _ _ _ _ _ _