0

if while/ do-を使用してwhile、私の仕事は、次のユーザーの入力 (文字列値) を逆の順序で出力することです。

例えば:

入力文字列値: "You are American" 逆順出力: "American are You"

これを行う方法はありますか?

私が試してみました

string a;
cout << "enter a string: ";
getline(cin, a);
a = string ( a.rbegin(), a.rend() );
cout << a << endl;
return 0;

...しかし、これは単語スペルの順序を逆にしますが、スペルは私が目指しているものではありません.

ifまた、 andステートメントを追加する必要がありますwhileが、その方法がわかりません。

4

6 に答える 6

5

アルゴリズムは次のとおりです。

  1. 文字列全体を逆にする
  2. 個々の単語を逆にする
#include<iostream>
#include<algorithm>
using namespace std;

string reverseWords(string a)
{ 
    reverse(a.begin(), a.end());
    int s = 0;
    int i = 0;
    while(i < a.length())
    {
        if(a[i] == ' ')
        {
             reverse(a.begin() + s, a.begin() + i);
             s = i + 1;
        }
        i++;
    }
    if(a[a.length() - 1] != ' ')  
    {
        reverse(a.begin() + s, a.end());           
    }
    return a; 
}
于 2013-01-01T09:27:17.713 に答える
1

この例では、入力文字列を一度に 1 単語ずつ展開し、逆の順序で連結して出力​​文字列を作成します。`

#include <iostream>
#include <sstream>

using namespace std;

int main()
{
  string inp_str("I am British");
  string out_str("");
  string word_str;
  istringstream iss( inp_str );


  while (iss >> word_str) {
    out_str = word_str + " " + out_str;
  } // while (my_iss >> my_word) 

  cout << out_str << endl;

  return 0;
} // main

`

于 2015-10-21T06:04:27.233 に答える
1

char *これは、スタックを使用して文字列の作成を最小限に抑える C++ コンパイラでコンパイルする C ベースのアプローチです。for最小限の作業で、これを C++ クラスを使用するように適応させることができ、さまざまなループをdo-whileorwhileブロックに簡単に置き換えることができます。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LINE_LENGTH 1000
#define MAX_WORD_LENGTH 80

void rev(char *str) 
{
    size_t str_length = strlen(str);
    int str_idx;
    char word_buffer[MAX_WORD_LENGTH] = {0};
    int word_buffer_idx = 0;

    for (str_idx = str_length - 1; str_idx >= 0; str_idx--)
        word_buffer[word_buffer_idx++] = str[str_idx];

    memcpy(str, word_buffer, word_buffer_idx);
    str[word_buffer_idx] = '\0';
}

int main(int argc, char **argv) 
{
    char *line = NULL;
    size_t line_length;
    int line_idx;
    char word_buffer[MAX_WORD_LENGTH] = {0};
    int word_buffer_idx;

    /* set up line buffer - we cast the result of malloc() because we're using C++ */

    line = (char *) malloc (MAX_LINE_LENGTH + 1);
    if (!line) {
        fprintf(stderr, "ERROR: Could not allocate space for line buffer!\n");
        return EXIT_FAILURE;
    }

    /* read in a line of characters from standard input */

    getline(&line, &line_length, stdin);

    /* replace newline with NUL character to correctly terminate 'line' */

    for (line_idx = 0; line_idx < (int) line_length; line_idx++) {
        if (line[line_idx] == '\n') {
            line[line_idx] = '\0';
            line_length = line_idx; 
            break;
        }
    }

    /* put the reverse of a word into a buffer, else print the reverse of the word buffer if we encounter a space */

    for (line_idx = line_length - 1, word_buffer_idx = 0; line_idx >= -1; line_idx--) {
        if (line_idx == -1) 
            word_buffer[word_buffer_idx] = '\0', rev(word_buffer), fprintf(stdout, "%s\n", word_buffer);
        else if (line[line_idx] == ' ')
            word_buffer[word_buffer_idx] = '\0', rev(word_buffer), fprintf(stdout, "%s ", word_buffer), word_buffer_idx = 0;
        else
            word_buffer[word_buffer_idx++] = line[line_idx];
    }

    /* cleanup memory, to avoid leaks */

    free(line);

    return EXIT_SUCCESS;
}

C++ コンパイラでコンパイルしてから使用するには:

$ g++ -Wall test.c -o test
$ ./test
foo bar baz
baz bar foo
于 2013-01-01T09:50:07.977 に答える
0

これは、とのそれぞれを1つだけ使用しifますwhile

#include <string>
#include <iostream>
#include <sstream>


void backwards(std::istream& in, std::ostream& out)
{
   std::string word;
   if (in >> word)   // Read the frontmost word
   {
      backwards(in, out);  // Output the rest of the input backwards...
      out << word << " ";  // ... and output the frontmost word at the back
   }
}

int main()
{
   std::string line;
   while (getline(std::cin, line))
   {
      std::istringstream input(line);
      backwards(input, std::cout);
      std::cout << std::endl;
   }
}
于 2013-01-01T15:41:24.570 に答える
0

このコードでは、文字列ライブラリを使用して入力ストリームの空白を検出し、それに応じて出力文を書き換えます。

アルゴリズムは 1 です。getline 関数を使用して入力ストリームを取得し、spacecs をキャプチャします。pos1 をゼロに初期化します。2. 入力ストリームの最初のスペースを探します 3. スペースが見つからない場合、入力ストリームは出力です 4. そうでない場合は、pos1 の後の最初の空白の位置、つまり pos2 を取得します。5. 出力文の先頭にある pos1 と pos2 の間の部分文字列を保存します。新しい文。6. これで、Pos1 はブランクの後の最初の文字になりました。7. スペースがなくなるまで、4、5、および 6 を繰り返します。8. newSentence の先頭に最後の部分文字列を追加します。–

#include <iostream> 
#include <string> 

  using namespace std; 

int main ()
{ 
    string sentence; 
    string newSentence;
    string::size_type pos1; 
    string::size_type pos2; 

    string::size_type len; 

    cout << "This sentence rewrites a sentence backward word by word\n"
            "Hello world => world Hello"<<endl;

    getline(cin, sentence); 
    pos1 = 0; 
    len = sentence.length();
    pos2 = sentence.find(' ',pos1); 
    while (pos2 != string::npos)
        {
            newSentence = sentence.substr(pos1, pos2-pos1+1) + newSentence; 
            pos1 = pos2 + 1;
            pos2 = sentence.find(' ',pos1);       
        }
    newSentence = sentence.substr(pos1, len-pos1+1) + " "  + newSentence;
    cout << endl << newSentence  <<endl; 

    return 0;

}
于 2015-06-08T09:02:13.157 に答える
0

区切り文字として ' ' (シングル スペース) 文字を使用してofを取得する際に、この解決策を試すことができます。vectorstring

次のステップは、このベクトルを逆方向​​に反復処理して逆文字列を生成することです。

これは次のようになります (splitは、その投稿の文字列分割関数です)。

編集 2 : 何らかの理由で s が気に入らない場合はvector、配列を使用できます (ポインターは配列として機能することに注意してください)。この例では、固定サイズの配列をヒープに割り当てます。これを変更して、現在の単語量が特定の値に達したときにサイズを 2 倍にすることができます。

arrayの代わりに を使用したソリューションvector:

#include <iostream>
#include <string>
using namespace std;

int getWords(string input, string ** output)
{
    *output = new string[256];  // Assumes there will be a max of 256 words (can make this more dynamic if you want)
    string currentWord;
    int currentWordIndex = 0;
    for(int i = 0; i <= input.length(); i++)
    {
        if(i == input.length() || input[i] == ' ')  // We've found a space, so we've reached a new word
        {
            if(currentWord.length() > 0)
            {
                (*output)[currentWordIndex] = currentWord;
                currentWordIndex++;
            }
            currentWord.clear();
        }
        else
        {
            currentWord.push_back(input[i]);    // Add this character to the current word
        }
    }
    return currentWordIndex;    // returns the number of words
}

int main ()
{
    std::string original, reverse;
    std::getline(std::cin, original);  // Get the input string
    string * arrWords;
    int size = getWords(original, &arrWords);  // pass in the address of the arrWords array
    int index = size - 1;
    while(index >= 0)
    {
       reverse.append(arrWords[index]);
       reverse.append(" ");
       index--;
    }
    std::cout << reverse << std::endl;
    return 0;
}

編集main:インクルード、関数、whileループ形式を追加

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


// From the post
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems)
{
   std::stringstream ss(s);
   std::string item;
   while(std::getline(ss, item, delim)) {
       elems.push_back(item);
   }
   return elems;
}


std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    return split(s, delim, elems);
}

int main ()
{
    std::string original, reverse;
    std::cout << "Input a string: " << std::endl;
    std::getline(std::cin, original);  // Get the input string

    std::vector<std::string> words = split(original, ' ');

    std::vector<std::string>::reverse_iterator rit = words.rbegin();

    while(rit != words.rend())
    {
       reverse.append(*rit);
       reverse.append(" "); // add a space
       rit++;
    }
    std::cout << reverse << std::endl;
    return 0;
}
于 2013-01-01T09:30:40.453 に答える