Reverse Words in a String
Reverse the order of words in a sentence, collapsing extra spaces.
Sample input
the sky is blue
Sample output
blue is sky the
Solution
s = "the sky is blue"
print(" ".join(reversed(s.split())))
const s = "the sky is blue";
console.log(s.trim().split(/\s+/).reverse().join(" "));
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
String s = "the sky is blue";
List<String> words = Arrays.asList(s.trim().split("\\s+"));
Collections.reverse(words);
System.out.println(String.join(" ", words));
}
}
fun main() {
val s = "the sky is blue"
println(s.trim().split(Regex("\\s+")).reversed().joinToString(" "))
}
let s = "the sky is blue"
let words = s.split(separator: " ").reversed()
print(words.joined(separator: " "))
void main() {
String s = 'the sky is blue';
print(s.trim().split(RegExp(r'\s+')).reversed.join(' '));
}
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main() {
string s = "the sky is blue";
stringstream ss(s);
string word;
vector<string> words;
while (ss >> word) words.push_back(word);
for (int i = words.size() - 1; i >= 0; i--) {
cout << words[i];
if (i > 0) cout << " ";
}
cout << endl;
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char s[] = "the sky is blue";
char *words[100];
int count = 0;
char *token = strtok(s, " ");
while (token != NULL) {
words[count++] = token;
token = strtok(NULL, " ");
}
for (int i = count - 1; i >= 0; i--) {
printf("%s", words[i]);
if (i > 0) printf(" ");
}
printf("\n");
return 0;
}