C ++使用指针反转字符串中单词的顺序

时间:2013-01-06 01:14:56

标签: c++ string pointers reverse

这是我尝试获取输入然后以相反的顺序生成带有单词的输出。注意:我只能使用指针。

    Input: What is your name? 
    Output: name? your is What

我已经看过这里发布的其他解决方案,并且尽可能地尝试实现它们,但我一直遇到问题。目前它只显示该行的第一个字母。我很感激任何帮助来解决它!

#include <iostream>
using namespace std;

#include <cstring>

int main( )
{
    char input[255] = {' '};
    char *head, *tail;
    char temp; 
    int i = 0; 

    cin >> input;

    head = input;
    tail = input;

    while(*tail!='\0')
    {
        tail++;
    }

    while (tail <= head){
        temp = *head;
        *head=*tail;
        *tail=temp;

        *head++;
        *tail--;
    }

    cout << input;
    cout << endl;

    return 0;
}

3 个答案:

答案 0 :(得分:3)

试试这个。没有任何东西引用STL。

#include <iostream>
#include <cstring>
using namespace std;
int main(int argc, char **argv)
{
    char input[255];
    char *head; // head of a word.
    char *tail; // tail of a word.
    cin.getline(input, 255); // read a whole line.
    tail = input + strlen(input) - 1; // if you can use <cstring>?
    while (tail >= input) {
        if (*tail == 0 || *tail == ' ') {
            tail--; // move to the tail of a word.
        } else {
            tail[1] = 0;
            head = tail;
            while (head >= input) {
                if (head == input || *(head - 1) == ' ') {
                    cout << head << " "; // output a word.
                    tail = head - 1; // seek the next word.
                    break;
                }
                head--; // move to the head of a word.
            }
        }
    }
    cout << endl;
    return 0;
} 

答案 1 :(得分:1)

这样的伪代码如何:

read_input_into_string();
trim_leading_and_trailing_whitespace();
convert_multiple_whitespace_in_string_to_single_space();

for (char* current_string_ptr = find_end_of_string();
     current_string_ptr > start_of_input;
     current_string_ptr--)
{
    if (*current_string_ptr == ' ')
    {
        // +1 because `current_string_ptr` is at the space,
        // and we want to print the word without leading spaces
        std::cout << (current_string_ptr + 1) << ' ';

        // Terminate string at the space
        *current_string_ptr = '\0';
    }
}

它不完整(即不会打印输入中的第一个单词),但我将其作为练习留给读者。 :)

答案 2 :(得分:0)

低电平:

void reverseStr(const char* str, char* szBuffer)
{
    int j = strlen(str) - 1, i = j, k = 0;
    if(j < 0)
        return;
    while(j >= 0){
        if(j-1 < 0 || *(str+j-1) == ' '){
            strncpy(szBuffer+k, str+j, i-j+1);
            szBuffer[k+i-j+1] = ' ';
            k += i-j+2;
            i = j-2;
            j -= 2;
        }
        else{
            --j;
        }
    }
    szBuffer[k-1] = '\0';
}

int main(int argc, char** argv)
{
    const char* str = "this is a string?";

    char szBuffer[256];
    reverseStr(str, szBuffer);

    std::cout << szBuffer;

}