Skip to content

Instantly share code, notes, and snippets.

@jakubpetrik
Created September 24, 2015 06:04
Show Gist options
  • Save jakubpetrik/39773fd7e71f175b98ed to your computer and use it in GitHub Desktop.
Save jakubpetrik/39773fd7e71f175b98ed to your computer and use it in GitHub Desktop.
Reverse words in a string.
/**
http://rosettacode.org/wiki/Reverse_words_in_a_string
The task is to reverse the order of all tokens in each of a number of strings and display the result;
the order of characters within a token should not be modified.
Example: “Hey you, Bub!” would be shown reversed as: “Bub! you, Hey”
Tokens are any non-space characters separated by spaces (formally, white-space);
the visible punctuation forms part of the word within which it is located and should not be modified.
You may assume that there are no significant non-visible characters in the input.
Multiple or superfluous spaces may be compressed into a single space.
Some strings have no tokens, so an empty string (or one just containing spaces) would be the result.
Display the strings in order (1st, 2nd, 3rd, ···), and one string per line.
(You can consider the ten strings as ten lines, and the tokens as words.)
*/
import Foundation
// convenience extension for better clarity
extension String {
var lines: [String] {
get {
return self.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
}
}
var words: [String] {
get {
return self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}
}
}
let input = "---------- Ice and Fire ------------\n\nfire, in end will world the say Some\nice. in say Some\ndesire of tasted I've what From\nfire. favor who those with hold I\n\n... elided paragraph last ...\n\nFrost Robert -----------------------\n"
print(input.lines.map { $0.words.reverse().joinWithSeparator(" ") }.joinWithSeparator("\n"))
/**
output:
------------ Fire and Ice ----------
Some say the world will end in fire,
Some say in ice.
From what I've tasted of desire
I hold with those who favor fire.
... last paragraph elided ...
----------------------- Robert Frost
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment