Created
April 18, 2014 19:44
-
-
Save w-vi/11061237 to your computer and use it in GitHub Desktop.
C string replace, string swap
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
#include <stdlib.h> | |
#include <assert.h> | |
#include <string.h> | |
#include <wchar.h> | |
/* | |
* Swap string | |
* Returns copy of the given string in the reverse order. | |
*/ | |
char * | |
strswp(const char *str) | |
{ | |
register int i = 0; | |
register int j = 0; | |
char *chr = NULL; | |
size_t len = 0; | |
assert(str != NULL); | |
len = strlen(str); | |
chr = (char *)malloc((len + 1) * sizeof(char)); | |
if(NULL == chr) return NULL; | |
j = (int)len -1; | |
for(i = 0; i < (int)len; ++i) | |
{ | |
chr[i] = str[j--]; | |
} | |
chr[i] = '\0'; | |
return chr; | |
} | |
wchar_t * | |
wcsswp(const wchar_t *wstr) | |
{ | |
register int i = 0; | |
register int j = 0; | |
wchar_t *wchr = NULL; | |
size_t len = 0; | |
assert(wstr != NULL); | |
len = wcslen(wstr); | |
wchr = (wchar_t *)malloc((len + 1) * sizeof(wchar_t)); | |
if(NULL == wchr) return NULL; | |
j = (int)len - 1; | |
for(i = 0; i < (int)len; ++i) | |
{ | |
wchr[i] = wstr[j--]; | |
} | |
wchr[i] = L'\0'; | |
return wchr; | |
} | |
/* | |
* Replace substring. | |
* Replaces given substring by another substring. | |
* Both substrings have to be the same length. | |
* Returns the number of replaced instances of the character or substring. | |
* Zero if the string is not changed. | |
*/ | |
int | |
strrpl(const char *str, const char *substr, const char *repl) | |
{ | |
register int i = 0; | |
char *chr = NULL; | |
size_t sub_len = 0; | |
size_t repl_len = 0; | |
assert(str != NULL); | |
assert(substr != NULL); | |
assert(repl != NULL); | |
chr = strstr(str, substr); | |
if(chr == NULL) return 0; | |
sub_len = strlen(substr); | |
repl_len = strlen(repl); | |
for(i = 0; i < (int)sub_len && i < (int)repl_len; ++i) | |
{ | |
*chr = repl[i]; | |
chr++; | |
if(chr == '\0') break; | |
} | |
return i; | |
} | |
int | |
wcsrpl(const wchar_t *wstr, const wchar_t *wsubstr, const wchar_t *wrepl) | |
{ | |
register int i = 0; | |
wchar_t *chr = NULL; | |
size_t sub_len = 0; | |
size_t repl_len = 0; | |
assert(wstr != NULL); | |
assert(wsubstr != NULL); | |
assert(wrepl != NULL); | |
chr = wcsstr(wstr, wsubstr); | |
if(chr == NULL) return 0; | |
sub_len = wcslen(wsubstr); | |
repl_len = wcslen(wrepl); | |
for(i = 0; i < (int)sub_len && i < (int)repl_len; i++) | |
{ | |
*chr = wrepl[i]; | |
chr++; | |
if(chr == '\0') break; | |
} | |
return i; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment