Phrase reversals: Difference between revisions
m (→{{header|Sidef}}: added the output section) |
|||
Line 12: | Line 12: | ||
* [[Reverse a string]] |
* [[Reverse a string]] |
||
* [[Reverse words in a string]] |
* [[Reverse words in a string]] |
||
=={{header|AutoHotKey}}== |
|||
<lang AutoHotKey>var = |
|||
( |
|||
Rosetta Code Phrase Reversal |
|||
) |
|||
array := strsplit(var, " ") |
|||
loop, % array.maxindex() |
|||
string .= array[array.maxindex() - A_index + 1] . " " |
|||
loop, % array.maxindex() |
|||
{ |
|||
m := array[A_index] |
|||
array2 := strsplit(m, "") |
|||
Loop, % array2.maxindex() |
|||
string2 .= array2[array2.maxindex() - A_index + 1] |
|||
string2 .= " " |
|||
} |
|||
array := strsplit(string, " " ) |
|||
loop, % array.maxindex() |
|||
{ |
|||
m := array[A_index] |
|||
array3 := strsplit(m, "") |
|||
Loop, % array3.maxindex() |
|||
string3 .= array3[array3.maxindex() - A_index + 1] |
|||
string3 .= " " |
|||
} |
|||
MsgBox % var . "`n" . string3 . "`n" . String . "`n" . string2 |
|||
ExitApp |
|||
esc::ExitApp</lang> |
|||
{{out}} |
|||
<pre>Rosetta Code Phrase Reversal |
|||
lasreveR esarhP edoC attesoR |
|||
Reversal Phrase Code Rosetta |
|||
attesoR edoC esarhP lasreveR |
|||
</pre> |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |
Revision as of 06:36, 28 December 2014
You are encouraged to solve this task according to the task description, using any language you may know.
Given a string of space separated words containing the following phrase:
- "rosetta code phrase reversal"
- Reverse the string.
- Reverse each individual word in the string, maintaining original string order.
- Reverse the order of each word of the phrase, maintaining the order of characters in each word.
Show your output here.
- See also
AutoHotKey
<lang AutoHotKey>var = ( Rosetta Code Phrase Reversal )
array := strsplit(var, " ")
loop, % array.maxindex() string .= array[array.maxindex() - A_index + 1] . " "
loop, % array.maxindex() { m := array[A_index] array2 := strsplit(m, "") Loop, % array2.maxindex() string2 .= array2[array2.maxindex() - A_index + 1] string2 .= " " }
array := strsplit(string, " " )
loop, % array.maxindex() { m := array[A_index] array3 := strsplit(m, "") Loop, % array3.maxindex() string3 .= array3[array3.maxindex() - A_index + 1] string3 .= " " }
MsgBox % var . "`n" . string3 . "`n" . String . "`n" . string2 ExitApp
esc::ExitApp</lang>
- Output:
Rosetta Code Phrase Reversal lasreveR esarhP edoC attesoR Reversal Phrase Code Rosetta attesoR edoC esarhP lasreveR
Ada
To split a string into words, the package "Simple_Parse" from another task [[1]] is used.
<lang Ada><with Ada.Text_IO, Simple_Parse;
procedure Phrase_Reversal is
function Reverse_String (Item : String) return String is Result : String (Item'Range); begin for I in Item'range loop Result (Result'Last - I + Item'First) := Item (I); end loop; return Result; end Reverse_String; function Reverse_Words(S: String) return String is Cursor: Positive := S'First; Word: String := Simple_Parse.Next_Word(S, Cursor); begin if Cursor > S'Last then -- Word holds the last word
return Reverse_String(Word);
else
return Reverse_String(Word) & " " & Reverse_Words(S(Cursor .. S'Last));
end if; end Reverse_Words; function Reverse_Order(S: String) return String is Cursor: Positive := S'First; Word: String := Simple_Parse.Next_Word(S, Cursor); begin if Cursor > S'Last then -- Word holds the last word
return Word;
else
return Reverse_Order(S(Cursor .. S'Last)) & " " & Word;
end if; end Reverse_Order; Phrase: String := "rosetta code phrase reversal"; use Ada.Text_IO;
begin
Put_Line("0. The original phrase: """ & Phrase & """"); Put_Line("1. Reverse the entire phrase: """ & Reverse_String(Phrase) & """"); Put_Line("2. Reverse words, same order: """ & Reverse_Words(Phrase) & """"); Put_Line("2. Reverse order, same words: """ & Reverse_Order(Phrase) & """");
end Phrase_Reversal;</lang>
- Output:
0. The original phrase: "rosetta code phrase reversal" 1. Reverse the entire phrase: "lasrever esarhp edoc attesor" 2. Reverse words, same order: "attesor edoc esarhp lasrever" 2. Reverse order, same words: "reversal phrase code rosetta"
AWK
<lang awk># Usage: awk -f phrase_revers.awk function rev(s, del, n,i,a,r) {
n = split(s, a, del) r = a[1] for(i=2; i <= n; i++) {r = a[i] del r } return r
}
BEGIN {
p0 = "Rosetta Code Phrase Reversal"
fmt = "%-20s: %s\n" printf( fmt, "input", p0 ) printf( fmt, "string reversed", rev(p0, "") ) wr = rev(p0, " ") printf( fmt, "word-order reversed", wr ) printf( fmt, "each word reversed", rev(wr) )
}</lang>
- Output:
input : Rosetta Code Phrase Reversal string reversed : lasreveR esarhP edoC attesoR word-order reversed : Reversal Phrase Code Rosetta each word reversed : attesoR edoC esarhP lasreveR
Bracmat
This example only works correctly with strings only consisting of byte-sized characters. <lang bracmat>( "rosetta code phrase reversal":?text & rev$!text:?output1 & get$(!text,MEM):?words & :?output2:?output3 & whl
' ( !words:%?word %?words & !output2 rev$!word " ":?output2 & " " !word !output3:?output3 )
& str$(!output2 rev$!words):?output2 & str$(!words !output3):?output3 & out
$ ( str $ ("0:\"" !text "\"\n1:\"" !output1 "\"\n2:\"" !output2 "\"\n3:\"" !output3 \"\n) )
);</lang> Output:
0:"rosetta code phrase reversal" 1:"lasrever esarhp edoc attesor" 2:"attesor edoc esarhp lasrever" 3:"reversal phrase code rosetta"
C
Working with C strings is often long-winded. <lang C>
- include <stdio.h>
- include <string.h>
/* The functions used are destructive, so after each call the string needs
* to be copied over again. One could easily allocate new strings as * required, but this way allows the caller to manage memory themselves */
char* reverse_section(char *s, size_t length) {
if (length == 0) return s;
size_t i; char temp; for (i = 0; i < length / 2 + 1; ++i) temp = s[i], s[i] = s[length - i], s[length - i] = temp; return s;
}
char* reverse_words_in_order(char *s, char delim) {
if (!strlen(s)) return s;
size_t i, j; for (i = 0; i < strlen(s) - 1; ++i) { for (j = 0; s[i + j] != 0 && s[i + j] != delim; ++j) ; reverse_section(s + i, j - 1); s += j; } return s;
}
char* reverse_string(char *s) {
return strlen(s) ? reverse_section(s, strlen(s) - 1) : s;
}
char* reverse_order_of_words(char *s, char delim) {
reverse_string(s); reverse_words_in_order(s, delim); return s;
}
int main(void) {
char str[] = "rosetta code phrase reversal"; size_t lenstr = sizeof(str) / sizeof(str[0]); char scopy[lenstr]; char delim = ' ';
/* Original String */ printf("Original: \"%s\"\n", str);
/* Reversed string */ strncpy(scopy, str, lenstr); reverse_string(scopy); printf("Reversed: \"%s\"\n", scopy);
/* Reversed words in string */ strncpy(scopy, str, lenstr); reverse_words_in_order(scopy, delim); printf("Reversed words: \"%s\"\n", scopy);
/* Reversed order of words in string */ strncpy(scopy, str, lenstr); reverse_order_of_words(scopy, delim); printf("Reversed order: \"%s\"\n", scopy);
return 0;
} </lang>
- Output:
Original: "rosetta code phrase reversal" Reversed: "lasrever esarhp edoc attesor" Reversed words: "attesor edoc esarhp lasrever" Reversed order: "reversal phrase code rosetta"
C++
<lang cpp>#include <iostream>
- include <vector>
- include <algorithm>
- include <string>
- include <boost/tokenizer.hpp>
void string_to_vector ( const std::string & input , std::vector<std::string> & words ) {
boost::tokenizer<> tok( input ) ; for ( boost::tokenizer<>::iterator beg = tok.begin( ) ; beg != tok.end( ) ; ++beg ) words.push_back( *beg ) ;
}
int main( ) {
std::string startphrase ( "rosetta code phrase reversal" ) ; std::cout << "Input : " << startphrase << '\n' ; std::string local_copy ( startphrase ) ; std::reverse ( local_copy.begin( ) , local_copy.end( ) ) ; std::cout << "Input reversed : " << local_copy << '\n' ; std::vector<std::string> words ; string_to_vector ( startphrase , words ) ; //copy the vector with the original words to reverse their order later std::vector<std::string> original_words ( words ) ; //reverse each word in the string std::cout << "Each word reversed : " ; for ( std::string word : words ) { std::reverse ( word.begin( ) , word.end( ) ) ; std::cout << word << " " ; } std::cout << '\n' ; std::cout << "Original word order reversed : " ; for ( std::vector<std::string>::const_reverse_iterator cri = original_words.rbegin( ) ;
cri != original_words.rend( ) ; cri++ ) {
std::cout << *cri << " " ; } std::cout << '\n' ; return 0 ;
} </lang>
- Output:
Input : rosetta code phrase reversal Input reversed : lasrever esarhp edoc attesor Each word reversed : attesor edoc esarhp lasrever Original word order reversed : reversal phrase code rosetta
D
Partially lazy. <lang d>void main() {
import std.stdio, std.range;
immutable phrase = "rosetta code phrase reversal"; phrase.retro.writeln; // Reversed string. phrase.splitter.map!retro.joiner(" ").writeln; // Words reversed. phrase.split.retro.joiner(" ").writeln; // Word order reversed.
}</lang>
- Output:
lasrever esarhp edoc attesor attesor edoc esarhp lasrever reversal phrase code rosetta
Go
Simple
<lang go>package main
import ( "fmt" "strings" )
const phrase = "rosetta code phrase reversal"
func revStr(s string) string { rs := make([]rune, len(s)) i := len(s) for _, r := range s { i-- rs[i] = r } return string(rs[i:]) }
func main() { fmt.Println("Reversed: ", revStr(phrase))
ws := strings.Fields(phrase) for i, w := range ws { ws[i] = revStr(w) } fmt.Println("Words reversed: ", strings.Join(ws, " "))
ws = strings.Fields(phrase) last := len(ws) - 1 for i, w := range ws[:len(ws)/2] { ws[i], ws[last-i] = ws[last-i], w } fmt.Println("Word order reversed:", strings.Join(ws, " ")) }</lang>
- Output:
Reversed: lasrever esarhp edoc attesor Words reversed: attesor edoc esarhp lasrever Word order reversed: reversal phrase code rosetta
Alternative
<lang go>package main
import ( "fmt" "regexp" "sort" "strings" )
const phrase = "rosetta code phrase reversal"
type reversible interface { Len() int Swap(i, j int) }
func reverse(p reversible) { mid := p.Len() / 2 last := p.Len() - 1 for i := 0; i < mid; i++ { p.Swap(i, last-i) } }
type runeSlice []rune
func (p runeSlice) Len() int { return len(p) } func (p runeSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func reverseString(s string) string { r := runeSlice(s) reverse(r) return string(r) }
var rx = regexp.MustCompile(`\S*`)
func reverseWords(s string) string { return rx.ReplaceAllStringFunc(s, func(m string) string { return reverseString(m) }) }
func reverseWordOrder(s string) string { l := sort.StringSlice(strings.Fields(s)) reverse(l) return strings.Join(l, " ") }
func main() { fmt.Println("Reversed: ", reverseString(phrase)) fmt.Println("Words reversed: ", reverseWords(phrase)) fmt.Println("Word order reversed:", reverseWordOrder(phrase)) }</lang>
- Output:
Reversed: lasrever esarhp edoc attesor Words reversed: attesor edoc esarhp lasrever Word order reversed: reversal phrase code rosetta
Haskell
<lang haskell>phrase = "rosetta code phrase reversal"
main = do
putStrLn $ reverse phrase putStrLn $ unwords . map reverse . words $ phrase putStrLn $ unwords . reverse . words $ phrase</lang>
- Output:
lasrever esarhp edoc attesor attesor edoc esarhp lasrever reversal phrase code rosetta
J
Solution: <lang j> getWords=: (' '&splitstring) :. (' '&joinstring)
reverseString=: |. reverseWords=: |.&.>&.getWords reverseWordOrder=: |.&.getWords</lang>
Usage: <lang j> phrase=: 'rosetta code phrase reversal'
(reverseWordOrder , reverseWords ,: reverseString) phrase
reversal phrase code rosetta attesor edoc esarhp lasrever lasrever esarhp edoc attesor</lang>
Java
<lang java5>import java.util.Arrays;
public class PhraseRev{ private static String reverse(String x){ return new StringBuilder(x).reverse().toString(); }
private static <T> T[] reverse(T[] x){ T[] rev = Arrays.copyOf(x, x.length); for(int i = x.length - 1; i >= 0; i--){ rev[x.length - 1 - i] = x[i]; } return rev; }
private static String join(String[] arr, String joinStr){ StringBuilder joined = new StringBuilder(); for(int i = 0; i < arr.length; i++){ joined.append(arr[i]); if(i < arr.length - 1) joined.append(joinStr); } return joined.toString(); }
public static void main(String[] args){ String str = "rosetta code phrase reversal";
System.out.println("Straight-up reversed: " + reverse(str)); String[] words = str.split(" "); for(int i = 0; i < words.length; i++){ words[i] = reverse(words[i]); } System.out.println("Reversed words: " + join(words, " ")); System.out.println("Reversed word order: " + join(reverse(str.split(" ")), " ")); } }</lang>
- Output:
Straight-up reversed: lasrever esarhp edoc attesor Reversed words: attesor edoc esarhp lasrever Reversed word order: reversal phrase code rosetta
jq
<lang jq>def reverse_string: explode | reverse | implode;
"rosetta code phrase reversal" | split(" ") as $words | "0. input: \(.)",
"1. string reversed: \(reverse_string)", "2. each word reversed: \($words | map(reverse_string) | join(" "))", "3. word-order reversed: \($words | reverse | join(" "))"</lang>
- Output:
$ jq -r -n -f Phrase_reversals.jq 0. input: rosetta code phrase reversal 1. string reversed: lasrever esarhp edoc attesor 2. each word reversed: attesor edoc esarhp lasrever 3. word-order reversed: reversal phrase code rosetta
Perl
<lang perl>my $s = "rosetta code phrase reversal"; my $rev_s = reverse($s); my $rev_ew = join(" ", reverse split(/ /,reverse $s)); my $rev_wo = join(" ", reverse split(/ /,$s));
printf "0. %-20s: %s\n", "input", $s; printf "1. %-20s: %s\n", "string reversed", $rev_s; printf "2. %-20s: %s\n", "each word reversed", $rev_ew; printf "3. %-20s: %s\n", "word-order reversed", $rev_wo;</lang>
- Output:
0. input : rosetta code phrase reversal 1. string reversed : lasrever esarhp edoc attesor 2. each word reversed : attesor edoc esarhp lasrever 3. word-order reversed : reversal phrase code rosetta
Perl 6
<lang perl6>my $s = 'rosetta code phrase reversal';
say 'Input : ', $s; say 'String reversed : ', $s.flip; say 'Each word reversed : ', $s.words».flip; say 'Word-order reversed : ', $s.words.reverse;</lang>
- Output:
Input : rosetta code phrase reversal String reversed : lasrever esarhp edoc attesor Each word reversed : attesor edoc esarhp lasrever Word-order reversed : reversal phrase code rosetta
PHP
<lang php><?php // Initialize a variable with the input desired $strin = "rosetta code phrase reversal";
// Show user what original input was echo "Input: ".$strin."\n";
// Show the full input reversed echo "Reversed: ".strrev($strin)."\n";
// reverse the word letters in place $str_words_reversed = ""; $temp = explode(" ", $strin); foreach($temp as $word) $str_words_reversed .= strrev($word)." ";
// Show the reversed words in place echo "Words reversed: ".$str_words_reversed."\n";
// reverse the word order while leaving the words in order
$str_word_order_reversed = "";
$temp = explode(" ", $strin);
for($i=(count($temp)-1); $i>=0; $i--)
$str_word_order_reversed .= $temp[$i]." ";
// Show the reversal of the word order while leaving the words in order echo "Word order reversed: ".$str_word_order_reversed."\n"; </lang>
Input: rosetta code phrase reversal Reversed: lasrever esarhp edoc attesor Words reversed: attesor edoc esarhp lasrever Word order reversed: reversal phrase code rosetta
Python
These examples use the extended slicing notation of [::-1]
to reverse strings and lists of strings:
<lang python>>>> phrase = "rosetta code phrase reversal"
>>> phrase[::-1] # Reversed.
'lasrever esarhp edoc attesor'
>>> ' '.join(word[::-1] for word in phrase.split()) # Words reversed.
'attesor edoc esarhp lasrever'
>>> ' '.join(word for word in phrase.split()[::-1]) # Word order reversed.
'reversal phrase code rosetta'
>>> </lang>
Racket
<lang racket>#lang racket/base (require
(only-in srfi/13 string-reverse) (only-in racket/string string-split string-join))
(define (phrase-reversal s)
(list (string-reverse s) (string-join (map string-reverse (string-split s))) (string-join (reverse (string-split s)))))
(for-each displayln (phrase-reversal "rosetta code phrase reversal"))</lang>
- Output:
lasrever esarhp edoc attesor attesor edoc esarhp lasrever reversal phrase code rosetta
REXX
version 1
Working with REXX (strings and words) is trivial. <lang rexx>s='rosetta code phrase reversal' r1=reverse(s) r2= Do i=1 To words(s)
r2=r2 reverse(word(s,i)) End
r2=strip(r2) r3= Do i=words(s) To 1 By -1
r3=r3 word(s,i) End
r3=strip(r3) Say "input : " s say "string reversed : " r1 say "each word reversed : " r2 say "word-order reversed : " r3</lang>
- Output:
input : rosetta code phrase reversal string reversed : lasrever esarhp edoc attesor each word reversed : attesor edoc esarhp lasrever word-order reversed : reversal phrase code rosetta
version 2
<lang rexx>/*REXX pgm reverses words and/or letters in a string in various ways. */ i=; p=; parse arg $; if $= then $="rosetta code phrase reversal"
do j=1 for words($); _=word($,j) i=i reverse(_) ; p=_ p end /*j*/
say ' the original phrase used: ' $ say ' original phrase reversed: ' reverse($) say 'reversed individual words: ' strip(i) say 'reversed words in phrases: ' p /*stick a fork in it, we're done.*/</lang> output when using the default string:
the original phrase used: rosetta code phrase reversal original phrase reversed: lasrever esarhp edoc attesor reversed individual words: attesor edoc esarhp lasrever reversed words in phrases: reversal phrase code rosetta
Ruby
<lang ruby>str = "rosetta code phrase reversal"
puts str.reverse # Reversed string. puts str.split.map(&:reverse).join(" ") # Words reversed. puts str.split.reverse.join(" ") # Word order reversed.</lang>
- Output:
lasrever esarhp edoc attesor attesor edoc esarhp lasrever reversal phrase code rosetta
Sidef
<lang ruby>var str = "rosetta code phrase reversal";
say str.reverse; # reversed string say str.words.map{.reverse}.join(' '); # words reversed say str.words.reverse.join(' '); # word order reversed</lang>
- Output:
lasrever esarhp edoc attesor attesor edoc esarhp lasrever reversal phrase code rosetta
Tcl
<lang tcl>set s "rosetta code phrase reversal"
- Reverse all characters
puts [string reverse $s]
- Reverse characters in each word
puts [lmap word $s {string reverse $word}]
- Reverse the words but not the characters
puts [lreverse $s]</lang>
- Output:
lasrever esarhp edoc attesor attesor edoc esarhp lasrever reversal phrase code rosetta
UNIX Shell
Version 1
Requires "rev" command.
<lang sh>s1="rosetta code phrase reversal" echo "Original string ----------------------> "$s1
echo -n "1.) Reverse the string ---------------> " echo $s1|rev
echo -n "2.) Reverse characters of each word --> " echo $s1|tr " " "\n"|rev|tr "\n" " ";echo
echo -n "3.) Reverse word order ---------------> " word_num=$(echo $s1|wc -w) while [ $word_num != 0 ];do echo -n $(echo $s1|cut -d " " -f $word_num);echo -n " " word_num=$(expr $word_num - 1);done;echo</lang>
- Output:
Original string ----------------------> rosetta code phrase reversal 1.) Reverse the string ---------------> lasrever esarhp edoc attesor 2.) Reverse characters of each word --> attesor edoc esarhp lasrever 3.) Reverse word order ---------------> reversal phrase code rosetta
Version 2
Does not require "rev" command.
<lang sh>s1="rosetta code phrase reversal" echo "Original string --> "$s1
echo -n "1.) Reverse the string --> " length=$(echo $s1|wc -c) while [ $length != 0 ];do echo $s1|cut -c$length|tr -d "\n" length=$(expr $length - 1) done;echo
echo -n "2.) Reverse characters of each word --> " word_quantity=$(echo $s1|wc -w) word_quantity=$(expr $word_quantity + 1) word_num=1 while [ $word_num != $word_quantity ];do length=$(echo $s1|cut -d " " -f $word_num|wc -c) while [ $length != 0 ];do echo $s1|cut -d " " -f $word_num|cut -c$length|tr -d "\n" length=$(expr $length - 1);done;echo -n " " word_num=$(expr $word_num + 1);done;echo
echo -n "3.) Reverse word order --> " word_num=$(echo $s1|wc -w) while [ $word_num != 0 ];do echo -n $(echo $s1|cut -d " " -f $word_num);echo -n " " word_num=$(expr $word_num - 1);done;echo</lang>
- Output:
Original string --> rosetta code phrase reversal 1.) Reverse the string --> lasrever esarhp edoc attesor 2.) Reverse characters of each word --> attesor edoc esarhp lasrever 3.) Reverse word order --> reversal phrase code rosetta
zkl
<lang zkl>zkl: var str="rosetta code phrase reversal" rosetta code phrase reversal
zkl: str.reverse() #1 lasrever esarhp edoc attesor
zkl: str.split().apply("reverse").concat(" ") #2 string to list to string attesor edoc esarhp lasrever
zkl: str.split().reverse().concat(" ") #3 reversal phrase code rosetta</lang>