字符串反转操作,网易的一道面试题

/**
*函数实现将网址进行如下操作
*www.google.com转成com.google.www 及mail.netease.com转成com.netease.mail
*
*不允许用STL,空间为0(1)
*
*C/C++ code
*
*void reverse(cha * ptr)
*{
*
*
*}
*
*
**/

char* find_next_right_dot(char *str)
{
    if(str == NULL)
        return NULL;

    char * src = str; //save the source string address

    while(*src) {
        if(*src++ == '.' && *src != '.' && *src != '\0') {
            //if the first char is dot and the follow char is not, and the string dont end with
            //0, get the char address after the last dot.
            return src;
        }
    }

    return NULL;
}

int find_first_dot(char *str)
{
    if(str == NULL)
        return -1;
    if(*str != '.')
        return 0;
    char *src = str;
    while(*src) {
        if(*src++ == '.' && *src != '.')
            return (int)(src - str);
    }

    return 0;
}

void reverse(char *begin, char *end)
{
    if(NULL == begin || end == NULL)
        return;
    char *tmp1 = begin;
    char *tmp2 = end;
    char a;

    while(tmp2 > tmp1) {
        a = *tmp1;
        *tmp1++ = *(tmp2);
        *tmp2-- = a;
    }

}


void reverse_by_dot(char *str)
{
    if(NULL == str)
        return;

    char *des = str;
    int firstdot = find_first_dot(str);
    des += firstdot;

    while(1) {

        if(*des++ == '.' && *des != '\0') {

            char *tmp = str + firstdot;
            char *dotstr = des - 2;//roll back to the char is not dot

            reverse(tmp, dotstr); //reverse the string from tmp to dotstr

            if(find_next_right_dot(dotstr)) {
                des = find_next_right_dot(dotstr);
                firstdot = des - str;
            } else {
                firstdot = des + 1 - str;
            }
        }

        if(*des == '\0') { // has reached the end of string des

            char *tmp = str + firstdot;
            char *dotstr = des - 1;
            reverse(tmp, dotstr);

            break;
        }


    }
}
int main(void)
{
    char *str = "neteasy.google.com";
    printf("%s\n", str);
    reverse(str, str + strlen(str) - 1);
    printf("reverse: %s\n", str);
    reverse_by_dot(str);
    printf("reverse_by_dot: %s\n", str);

    char *str1 = "...hello...world...";
    printf("\n%s\n", str1);
    reverse(str1, str1 + strlen(str1) - 1);
    printf("reverse: %s\n", str1);
    reverse_by_dot(str1);
    printf("reverse_by_dot: %s\n", str1);

    char *str2 = "hello world";
    printf("\n%s\n", str2);
    reverse(str2, str2 + strlen(str2) - 1);
    printf("reverse: %s\n", str2);
    reverse_by_dot(str2);
    printf("reverse_by_dot: %s\n", str2);

    return 0;
}

原文地址:https://www.cnblogs.com/jojodru/p/2487467.html