Skip to content

Instantly share code, notes, and snippets.

@webgtx
Last active February 3, 2023 05:43
Show Gist options
  • Save webgtx/6882ab51b3726d5bc155a47d75c21576 to your computer and use it in GitHub Desktop.
Save webgtx/6882ab51b3726d5bc155a47d75c21576 to your computer and use it in GitHub Desktop.
How to reverse string in C
#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