A left-handed string and a string that determines whether one string is the left-handed string of another string

The left-handed string is a frequently asked question in an interview. It seems to be very difficult. In fact, it is not as difficult as you think. Next, I use two methods to implement the left-handed string.
Method 1
Circulation left shift method
If you want to rotate two bits to the left, save the first two bits in the string in another string str, and then move the whole string in the remaining sub forward. Finally, the string in sub and str can be combined to get the desired left-handed string.
The specific code is as follows

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void StringRverse(char *pStr,int steps)
{
    int length=0,i=0;
    char *sub=pStr,*str;
    while(*pStr !='\0')
    {
        length++;
        pStr++;
    }
    pStr--;

    if(steps > length)
         steps=steps-length;
    str=(char *)malloc(steps);


    for(i=0;i<steps;i++)
        str[i]=sub[i];

    for(i=0;i<length-steps;i++)
        sub[i]=sub[length-steps+i-2];

    for(i=0;i<steps;i++)
        sub[length-steps+i]=str[i];
}


int main()
{
    char a[]="abcdef";
    printf("The initial string is: \n%s\n",a);
    StringRverse(a,2);
    printf("After two left-handed positions: \n%s\n",a);

    system("pause");
    return 0;

* method two
Double string method
The algorithm of double string method is not easy to think about but well implemented, because its implementation calls the library function of string copy. The specific method is to copy the string STR to another string sub, and then connect the two strings to get double strings. If you want to add two left-handed digits, copy from the third character in the sub string, copy the length, copy to the str string, so that the str string is left-handed
The code is as follows

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
void StringRverse(char *pStr,int steps)
{
    int length=0;
    char *sub=pStr;

    while( *sub !='\0')
    {
        length++;
        sub++;
    }

    char *tmp=(char *)malloc (sizeof(char)*length*2);
    assert(tmp);
    strcpy(tmp,pStr);
    strcat(tmp,pStr);
    strncpy(pStr,tmp+steps,length);

}


int main()
{
    char a[]="abcdef";

    printf("The initial string is: \n%s\n",a);
    StringRverse(a,2);
    printf("After two left-handed positions: \n%s\n",a);

    system("pause");
    return 0;
}

Posted by xlordt on Sun, 05 Apr 2020 18:15:08 -0700