string 反转字符串中单词的顺序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1009160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:28:04  来源:igfitidea点击:

Reverse the ordering of words in a string

algorithmdata-structuresstring

提问by Arnkrishn

I have this string s1 = "My name is X Y Z"and I want to reverse the order of the words so that s1 = "Z Y X is name My".

我有这个string s1 = "My name is X Y Z",我想颠倒单词的顺序,以便s1 = "Z Y X is name My".

I can do it using an additional array. I thought hard but is it possible to do it inplace (without using additional data structures) and with the time complexity being O(n)?

我可以使用额外的数组来做到这一点。我想得很努力,但是否有可能就地进行(不使用额外的数据结构)并且时间复杂度为 O(n)?

回答by Bill the Lizard

Reverse the entire string, then reverse the letters of each individual word.

反转整个字符串,然后反转每个单词的字母。

After the first pass the string will be

第一次通过后,字符串将是

s1 = "Z Y X si eman yM"

and after the second pass it will be

在第二遍之后,它将是

s1 = "Z Y X is name My"

回答by Demi

reverse the string and then, in a second pass, reverse each word...

反转字符串,然后在第二遍中反转每个单词...

in c#, completely in-place without additional arrays:

在 c# 中,完全就地,无需额外的数组:

static char[] ReverseAllWords(char[] in_text)
{
    int lindex = 0;
    int rindex = in_text.Length - 1;
    if (rindex > 1)
    {
        //reverse complete phrase
        in_text = ReverseString(in_text, 0, rindex);

        //reverse each word in resultant reversed phrase
        for (rindex = 0; rindex <= in_text.Length; rindex++)
        {
            if (rindex == in_text.Length || in_text[rindex] == ' ')
            {
                in_text = ReverseString(in_text, lindex, rindex - 1);
                lindex = rindex + 1;
            }
        }
    }
    return in_text;
}

static char[] ReverseString(char[] intext, int lindex, int rindex)
{
    char tempc;
    while (lindex < rindex)
    {
        tempc = intext[lindex];
        intext[lindex++] = intext[rindex];
        intext[rindex--] = tempc;
    }
    return intext;
}

回答by Demi

Not exactly in place, but anyway: Python:

>>> a = "These pretzels are making me thirsty"
>>> " ".join(a.split()[::-1])
'thirsty me making are pretzels These'

回答by Wrameerez

In Smalltalk:

在 Smalltalk 中:

'These pretzels are making me thirsty' subStrings reduce: [:a :b| b, ' ', a]

I know noone cares about Smalltalk, but it's so beautiful to me.

我知道没有人关心 Smalltalk,但它对我来说太美妙了。

回答by baumgart

You cannot do the reversal without at least some extra data structure. I think the smallest structure would be a single character as a buffer while you swap letters. It can still be considered "in place", but it's not completely "extra data structure free".

如果没有至少一些额外的数据结构,您就无法进行逆转。我认为在交换字母时,最小的结构是单个字符作为缓冲区。它仍然可以被认为是“就地”,但它并不是完全“没有额外的数据结构”。

Below is code implementing what Bill the Lizard describes:

下面是实现蜥蜴比尔描述的代码:

string words = "this is a test";

// Reverse the entire string
for(int i = 0; i < strlen(words) / 2; ++i) {
  char temp = words[i];
  words[i] = words[strlen(words) - i];
  words[strlen(words) - i] = temp;
}

// Reverse each word
for(int i = 0; i < strlen(words); ++i) {
  int wordstart = -1;
  int wordend = -1;
  if(words[i] != ' ') {
    wordstart = i;
    for(int j = wordstart; j < strlen(words); ++j) {
      if(words[j] == ' ') {
        wordend = j - 1;
        break;
      }
    }
    if(wordend == -1)
      wordend = strlen(words);
    for(int j = wordstart ; j <= (wordend + wordstart) / 2 ; ++j) {
      char temp = words[j];
      words[j] = words[wordend - (j - wordstart)];
      words[wordend - (j - wordstart)] = temp;
    }
    i = wordend;
  }
}

回答by Alex S

What language? If PHP, you can explode on space, then pass the result to array_reverse.

什么语言?如果是 PHP,则可以在空间上爆炸,然后将结果传递给 array_reverse。

If its not PHP, you'll have to do something slightly more complex like:

如果它不是 PHP,你将不得不做一些稍微复杂的事情,比如:

words = aString.split(" ");
for (i = 0; i < words.length; i++) {
    words[i] = words[words.length-i];
}

回答by Alex S

public static String ReverseString(String str)
{
    int word_length = 0;
    String result = "";
    for (int i=0; i<str.Length; i++)
    {
        if (str[i] == ' ')
        {
            result = " " + result;
            word_length = 0;
        } else 
        {
            result = result.Insert(word_length, str[i].ToString());
            word_length++;
        }
    }
    return result;
}

This is C# code.

这是 C# 代码。

回答by Kaymatrix

In Python...

ip = "My name is X Y Z"
words = ip.split()
words.reverse()
print ' '.join(words)

Anyway cookamunga provided good inline solution using python!

不管怎样,cookamunga 使用 python 提供了很好的内联解决方案!

回答by Nikola Mitev

class Program
{
    static void Main(string[] args)
    {
        string s1 =" My Name varma:;
        string[] arr = s1.Split(' ');
        Array.Reverse(arr);
        string str = string.Join(" ", arr);
        Console.WriteLine(str);
        Console.ReadLine();

    }
}

回答by AbhinavChoudhury

This is assuming all words are separated by spaces:

这是假设所有单词都用空格分隔:

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

int main()
{
    char string[] = "What are you looking at";
    int i, n = strlen(string);

    int tail = n-1;
    for(i=n-1;i>=0;i--)
    {
        if(string[i] == ' ' || i == 0)
        {
            int cursor = (i==0? i: i+1);
            while(cursor <= tail)
                printf("%c", string[cursor++]);
            printf(" ");
            tail = i-1;
        }
    }
    return 0;
}