Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Challenges

Comments on Reverse an ASCII string

Parent

Reverse an ASCII string

+11
−0

Your goal is to reverse an ascii string. Given a (optionally newline or null terminated) input, output your input in reverse order, optionally followed by a newline. Terminate afterward. Function answers will not be given a newline, and are not expected to output one unless they print the answer to console.

Examples

Assume all inputs are followed by a newline, and are all standard ASCII encoded.

abcdef -> fedcba
Hello, World! -> !dlroW ,olleH
racecar -> racecar

Example program

function solution(x) {
    return x.split("").reverse().join("");
}

Further clarifications

  • No, you don't have to handle nulls correctly.
  • Nor empty inputs.
History
Why does this post require moderator attention?
You might want to add some details to your flag.
Why should this post be closed?

1 comment thread

General comments (7 comments)
Post
+5
−0

C, 66 59 bytes

-7 bytes thanks to Lundin!


In-place string reversal

f(char*s){s[1]?f(s+1):0;for(char t=*s;s[1];*++s=t)*s=s[1];}

Try it online!

History
Why does this post require moderator attention?
You might want to add some details to your flag.

1 comment thread

General comments (4 comments)
General comments
Lundin‭ wrote over 3 years ago

I think this might be a possible improvement: f(char*s){s[1]?f(s+1):0;while(s[1]){char t=*s;*s=s[1];*++s=t;}}}. In case s[1] is a character, it makes the recursive call and then while loop. If not, a 0; dummy statement. s[1] is zero in that case so the while loop isn't executed.

Lundin‭ wrote over 3 years ago · edited over 3 years ago

Also, switching while with for will save you lots. for(char t=*s;s[1];*++s=t;)*s=s[1]; should work. So how about this? f(char*s){s[1]?f(s+1):0;for(char t=*s;s[1];*++s=t)*s=s[1];}, 59 bytes.

Moshi‭ wrote over 3 years ago · edited over 3 years ago

@Lundin Thanks for your suggestions!

Lundin‭ wrote over 3 years ago

Oh, and t actually doesn't have to be char. So with gcc implicit int abuse, this should be possible: t;f(char*s){s[1]?f(s+1):0;for(t=*s;s[1];*++s=t)*s=s[1];}.