forked from WebClub-NITK/Hacktoberfest-2k17
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request WebClub-NITK#400 from incinirate/patch-1
Add string reverse implementation
- Loading branch information
Showing
1 changed file
with
35 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
#include <stdio.h> | ||
#include <string.h> | ||
|
||
#define MAX_STRING 256 | ||
|
||
char *strrev(char *str) { | ||
char *p1, *p2; | ||
|
||
// Ensure the string exists and has data | ||
if (! str || ! *str) | ||
return str; | ||
|
||
// Flip the characters on the ends of the string, progressing inward towards the string center | ||
for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2) { | ||
*p1 ^= *p2; | ||
*p2 ^= *p1; | ||
*p1 ^= *p2; | ||
} | ||
|
||
return str; | ||
} | ||
|
||
void main() { | ||
char str[MAX_STRING + 2]; // Two extra bytes, one for the newline (\n) and one for the NULL terminator | ||
|
||
printf("\nEnter String: "); | ||
fgets(str, MAX_STRING + 2, stdin); | ||
|
||
str[strlen(str) - 1] = (char)NULL; | ||
|
||
printf("Original: %s\n", str); | ||
printf("Reversed: %s\n", strrev(str)); | ||
|
||
return 0; | ||
} |