Skip to content

Instantly share code, notes, and snippets.

@dimavs
Created May 3, 2011 09:24
Show Gist options
  • Save dimavs/953065 to your computer and use it in GitHub Desktop.
Save dimavs/953065 to your computer and use it in GitHub Desktop.
reverse string and replace '\' symbols with '/'
#include <stdio.h>
#include <string.h>
unsigned int reverse_and_replace(unsigned char* str)
{
unsigned int replace_count = 0;
unsigned int str_len = 0;
const unsigned char from = '\\';
const unsigned char to = '/';
int i;
if (str == NULL)
return 0;
str_len = strlen(str);
for (i = 0; i < str_len/2; i++) // we can use str_len >> 1 or another variable
{ // but compiler will optimise it for us
unsigned char ch;
if (str[i] == from)
{
str[i] = to;
replace_count++;
}
ch = str[i];
str[i] = str[str_len - i - 1];
str[str_len - i - 1] = ch;
if (str[i] == from)
{
str[i] = to;
replace_count++;
}
}
// check middle char
if ((str_len % 2) && (str[str_len/2] == from))
{
str[str_len/2] = to;
replace_count++;
}
return replace_count;
}
int main()
{
int ret = 0;
char* test1 = NULL;
struct _test {
char str[20];
char str_rev[20];
int replaces;
} test[] = {
{ "abc\\123", "321/cba", 1 }, // Test string with odd number of chars
{ "ab\\c\\01234", "43210/c/ba", 2 }, // Test string with even number of chars
{ "", "", 0 }, // Test empty string
};
int i;
// Test NULL
int num = reverse_and_replace(test1);
if (num != 0 || test1 != NULL)
{
printf ("TEST FAILED: string = %s, number of symbols converted\n", test1, num);
ret = 1;
}
// All other tests
for (i = 0; i < sizeof(test)/sizeof(test[0]); i++)
{
num = reverse_and_replace(test[i].str);
if (test[i].replaces != num || strncmp(test[i].str, test[i].str_rev, strlen(test[i].str)) != 0)
{
printf ("TEST FAILED: string = %s, number of symbols converted\n", test[i].str, num);
ret = 1;
}
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment