如何在不使用内置函数的情况下反转句子中的单词? [英] How can I reverse the words in a sentence without using built-in functions?

查看:118
本文介绍了如何在不使用内置函数的情况下反转句子中的单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是面试问题:

如何将 Dogs like cats 转换为 cats like Dogs ?

How to convert Dogs like cats to cats like Dogs ?

我的代码显示: cats like cats .我在哪里犯错?

My code shows: cats like cats. Where am I making the mistakes?

#include <iostream>
using namespace std;

int main()
{
    char sentence[] = ("dogs like cats");
    cout << sentence << endl;

    int len = 0;

    for (int i = 0; sentence[i] != '\0'; i++)
    {
        len++;
    }
    cout << len << endl;

    char reverse[len];
    int k = 0;

    for (int j = len - 1; j >= 0; j--)
    {
        reverse[k] = sentence[j];
        k++;
    }

    cout << reverse << endl;

    int words = 0;
    char str[len];

    for (int l = 0; reverse[l] != '\0'; l++)
    {
        if (reverse[l] == ' ' || reverse[l] == '\0') // not sure about this part
        {
            for (int m = l; m >= 0; m--)
            {
                str[words] = reverse[m];
                words++;
            }
        }
    }

    cout << str;

    return 0;
}

我知道您可以使用指针,堆栈,向量...来完成此操作,但是面试官对此并不感兴趣!

I know you can do this using pointers, stack, vectors... but interviewer was not interested in that!

推荐答案

这是示例代码的固定版本:

This is a fixed version of your sample code:

  • 您的主要问题是,每次找到并' ''\0'时,都将反向字符串的字节从头复制到该点.在loop 5中的示例以相反的顺序从索引0-5(stac)从reverse复制到str,但是在loop 10中,您从stac ekil)复制>到str的相反顺序,直到这里您已经打印了结果字符串('cats like cats'),并且在loop 15中相同,所有这些都增加了str的索引,在最后一个循环中,您是写入通过str有效内存的末尾(并且由于未打印为输出).
  • 您需要跟踪最后一个单词反转的结束时间,以便仅反转实际单词,而不是从开头到实际索引的字符串.
  • 您不想在单词的倒序中计算特殊字符('和'\ 0'),您将以cats like\0dogs
  • 结尾
  • Your principal problem is that every time you found and ' ' or '\0' you copy the bytes of the reverse string from the beginning to that point. Example in loop 5 you copy from index 0-5 (stac) from reverse to str in reverse order, but in in loop 10 you copy from index 0-10 (stac ekil) from reverse to str in reverse order, until here you have already the printed result string ('cats like cats'), and the same in loop 15 all of this incrementing the index of str, in the last loop you are written pass the end of the valid memory of str (and because of that not printed as output).
  • You need to keep track when end the last word reversed to reverse only the actual word, and not the string from the beginning to the actual index.
  • You don't want to count the special character (' ' and '\0') in the reversing of the words, you would end with cats like\0dogs

提供了修改后的示例代码:

Modified sample code provided:

#include <iostream>
using namespace std;

int main() {
    char sentence[] = ("dogs like cats");
    cout << sentence << endl;

    int len = 0;

    for (int i = 0; sentence[i] != '\0'; i++) {
        len++;
    }
    cout << len << endl;

    char reverse[len];
    int k = 0;

    for (int j = len - 1; j >= 0; j--) {
        reverse[k] = sentence[j];
        k++;
    }

    cout << reverse << endl;

    int words = 0;
    char str[len];

    // change here added last_l to track the end of the last word reversed, moved
    // the check of the end condition to the end of loop body for handling the \0
    // case
    for (int l = 0, last_l = 0; ; l++) {
        if (reverse[l] == ' ' || reverse[l] == '\0')
        {
            for (int m = l - 1; m >= last_l; m--) { // change here, using last_t to
                str[words] = reverse[m];            // only reverse the last word
                words++;                            // without the split character
            }
            last_l = l + 1;                         // update the end of the last
                                                    // word reversed
            str[words] = reverse[l];                // copy the split character
            words++;
        }
        if (reverse[l] == '\0')                     // break the loop
            break;
    }

    cout << str << endl;

    return 0;
}

某些代码在使用该语言最简单的功能的限制下编写.

Some code, written with the restriction of using the most simple features of the language.

#include <iostream>

// reverse any block of text.
void reverse(char* left, char* right) {
    while (left < right) {
        char tmp = *left;
        *left = *right;
        *right = tmp;

        left++;
        right--;
    }
}

int main() {
    char sentence[] = "dogs like cats";
    std::cout << sentence << std::endl;

    // The same length calculation as sample code.
    int len = 0;
    for (int i = 0; sentence[i] != '\0'; i++) {
        len++;
    }
    std::cout << len << std::endl;

    // reverse all the text (ex: 'stac ekil sgod')
    reverse(sentence, sentence + len - 1);

    // reverse word by word.
    char* end = sentence;
    char* begin = sentence;
    while (end < sentence + len) {
        if (*end != ' ')
            end++;

        if (end == sentence + len || *end == ' ') {
            reverse(begin, end - 1);
            begin = end + 1;
            end = begin;
        }
    }

    std::cout << sentence << std::endl;

    return 0;
}

这篇关于如何在不使用内置函数的情况下反转句子中的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆