String reverse, few kinds of methods

C:

1.If you can know the length of array(In this case which is size_t len), use this:

char *revstr(char *str, size_t len)
{

    char    *start = str;
    char    *end = str + len - 1;
    char    ch;//temp to store, to implement reverse in-place

    if (str != NULL)
    {
        while (start < end)
        {
            ch = *start;
            *start++ = *end;
            *end-- = ch;
        }
    }
    return str;
}

2.If did not pass string length in, get it first. This is another methods:

char * __cdecl _strrev (char * string)
{
        char *start = string;//store the start address to return
        char *left = string;//left
        char ch;//tmp 

        while (*string++)                 /* find end of string */
                ;
        string -= 2;//minus 2 because '\0' and null

        while (left < string)//left         {
                ch = *left;//store left
                *left++ = *string;//replace left
                *string-- = ch;//replace right
        }

        return(start);
}

Expand Question: Contain numbers, skip numbers and converse the characters.

char * skip_nums_converse_string(char * string)

{

    char * begin=string;

    char *lef=string;//pointer

    int len=strlen(string);

    char *new=(char*)malloc(sizeof(char)*len);//to return

    memset(new,0,len);

    stack S;

    int i = 0;

 

    while(*left)

    {

            while(*left&&('0'<*left&&*left<'9')){left++;}

            S.push(*left);

            left++;

    }

 

    while(!S.empty()&&i

    {

            new[i++]=S.pop();

    }

    new[len-1]='\0';

    return new;

}

C++:

Std function:

std:: void reverse(s.begin(), s.end());
If you want to assign into other string, use this:
s1.assign(s.rbegin(), s.rend());
This works well too.

Notes:

Can NOT converset a constant literal string. Such as:

 

The problem is that you're trying to reverse a constant literal string, which is read only. Change the declaration of a in main to char a[] = "12"; to make it a writable char array instead

你可能感兴趣的:(字符串处理)