Author |
Topic: String Reversal (Read 2584 times) |
|
cmdrdran
Newbie
Posts: 3
|
|
String Reversal
« on: Jul 24th, 2002, 3:05am » |
Quote Modify
|
This is what Perl is good at: String Manipulation! ########################################## #!/usr/bin/perl $str_to_rev = <STDIN>; chomp $str_to_rev; @rightways_str = split(/ /, $str_to_rev); my @reversed; foreach $word (@rightways_str) { unshift(@reversed, $word); } $str_rev = join(' ', @reversed); print "\n", $str_rev, "\n"; exit; ##########################################
|
|
IP Logged |
|
|
|
suid
Guest
|
On the other hand, this does not make it optimized for either speed or size. (if i'm not mistaken, that was part of the problem).
|
|
IP Logged |
|
|
|
ChOas
Guest
|
Hint: 'reverse' in Perl, in List context, returns what ? spoiler: #!/usr/bin/perl -w use strict; $_=<STDIN>; print join ' ',reverse split;
|
|
IP Logged |
|
|
|
S. Owen
Full Member
Gender:
Posts: 221
|
|
Re: String Reversal
« Reply #3 on: Jul 27th, 2002, 1:39pm » |
Quote Modify
|
You perl people! This problem is only challenging if you have to consider a lower-level implementation and the efficiency of it. The point is that it's a real mess to try to write code that would literally swap the words around in a character array (without perl of course). The slick answer is to reverse the whole string, then reverse each word individually.
|
|
IP Logged |
|
|
|
Ramkumar Rajendran
Guest
|
When each word of the sentence is reversed " The dog is wagging its tail " we get " ehT god si gniggaw sti liat " and when we reverse this sentence, we get " tail its wagging is dog The"
|
|
IP Logged |
|
|
|
Moonz
Guest
|
c++ code for this ... dont know if we can optimize it anymore !! I've used recursion ... that might be an some extra memory Use blindreverse() to reverse the whole string blindly and then use reverse() on that string to modify into the desired output. void blindreverse(std::string& val) { char *temp = (char *)val.c_str(); int len = val.length(); int x= 0; int y = len -1; while (x < y) { char save = temp[y]; temp[y] = temp[x]; temp[x] = save; x++; y--; } } void reverse (std::string& val) { int x= val.find_first_of(" "); if (x == std::string::npos) { blindreverse(val); } else { std::string temp = val.substr(0,x); std::string recurse = val.substr (x+1,val.length()); blindreverse(temp); reverse(recurse); val = temp +" "+recurse; } }
|
|
IP Logged |
|
|
|
Sir Col
Uberpuzzler
impudens simia et macrologus profundus fabulae
Gender:
Posts: 1825
|
|
Re: String Reversal
« Reply #7 on: Aug 25th, 2003, 7:35am » |
Quote Modify
|
How about PHP... ? Code:function reverse($s) { if (!strstr($s," ")) return $s; $a=explode(" ",$s); $s=$a[count($a)-1]; for ($i=count($a)-2;$i>=0;$i--) $s.=" $a[$i]"; return $s; } |
| Of course the 1st line in the function is only included to trap errors. For complete optimaility, the 2nd, 3rd, and 4th lines of code are all that are really needed.
|
|
IP Logged |
mathschallenge.net / projecteuler.net
|
|
|
|