Last active
February 3, 2023 05:43
-
-
Save webgtx/6882ab51b3726d5bc155a47d75c21576 to your computer and use it in GitHub Desktop.
How to reverse string in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
// My solution | |
void rvrs(char * str, char * reversed_str, unsigned len) { | |
str += len - 1; | |
while (str[0]) { | |
*reversed_str = str[0]; | |
str -= 1; | |
reversed_str++; | |
} | |
} | |
// I found this solution somewhere from internet | |
char *strrev (char *string) { | |
unsigned len = strlen(string); | |
int tmp; | |
for (unsigned idx = 0; idx < len/2; idx++) { | |
tmp = string[idx]; | |
string[idx] = string[len - idx - 1]; | |
string[len - idx - 1] = tmp; | |
} | |
return string; // reverse the string in place and return it | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment