Skip to content

Instantly share code, notes, and snippets.

@oguz-ismail
Last active November 19, 2022 17:23
Show Gist options
  • Save oguz-ismail/975ee0c03648f470cb8f54d37bc798b5 to your computer and use it in GitHub Desktop.
Save oguz-ismail/975ee0c03648f470cb8f54d37bc798b5 to your computer and use it in GitHub Desktop.
reverse string using libunistring routines
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <uniconv.h>
#include <unigbrk.h>
#include <unistr.h>
int
reverse(uint8_t *str) {
size_t len;
size_t glen;
uint8_t *temp;
const uint8_t *src;
uint8_t *dest;
const uint8_t *next;
const uint8_t *end;
temp = u8_strdup(str);
if (!temp)
return 0;
len = u8_strlen(str);
end = str + len;
src = str;
dest = temp + len;
while ((next = u8_grapheme_next(src, end))) {
glen = next - src;
dest -= glen;
u8_cpy(dest, src, glen);
src = next;
}
u8_cpy(str, temp, len);
free(temp);
return 1;
}
int
main(int argc, char *argv[]) {
int i;
uint8_t *str;
char *rstr;
setlocale(LC_ALL, "");
for (i = 1; i < argc; i++) {
str = u8_strconv_from_locale(argv[i]);
if (!str) {
perror(argv[i]);
continue;
}
if (!reverse(str)) {
perror(argv[i]);
goto end;
}
rstr = u8_strconv_to_locale(str);
if (!rstr) {
perror(argv[i]);
goto end;
}
printf("%s\n", rstr);
free(rstr);
end:
free(str);
}
}
void
strwrev(char *p) {
char *a, *b;
while (*p) {
for (a = p; isspace(*a); a++);
for (p = a; *p && !isspace(*p); p++);
for (b = p - 1; a < b; a++, b--) {
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
}
}
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* reverse substring between A and B in-place */
void
ssrev(char *a, char *b) {
for (; a < b; a++, b--) {
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
}
/* reverse string S in-place */
void
srev(char *s) {
ssrev(s, s + strlen(s) - 1);
}
/* reverse words in string S in-place */
void
swrev(char *s) {
char *w;
while (*s) {
for (w = s; isspace(*w); w++);
for (s = w; *s && !isspace(*s); s++);
ssrev(w, s - 1);
}
}
int
main(int argc, char *argv[]) {
char *s;
s = strdup(argv[1]);
srev(s);
swrev(s);
puts(s);
free(s);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment