Wednesday, 28 June 2017

String functions


/* Function to concatenate string t to end of s; return s */
char *myStrcat(char *s, const char *t)
{
 char *p = s;
 if (s == NULL || t == NULL)
 return s; /* we need not have to do anything */
 
 while (*s)
     s++;
 while (*s++ = *t++);
 return p;
}
 
 
/*String Length*/
 
int my_strlen(char *s)
{
 char *p=s;
 while(*p!='\0')
 p++;
 return(p-s);
} 
 
 
/*String Compare*/
strcmp(char *s1, char *s2)
{
    while (*s1==*s2)
    {
        if(*s1=='\0')
           return(0);
        s1++;
        s2++;
    }
    return(*s1-*s2);
}
 
 
/*reverse a string*/
char* rev(char* str)
{
    int end = strlen(str) - 1;
    int start = 0;

    while (start < end)
    {
        str[start] ^= str[end];
        str[end] ^= str[start];
        str[start] ^= str[end];

        ++start;
        --end;
    }

    return str;
} 
 
Another Example on String Reverse 
I am a good boy  ==> boy good a am I 
Step1: Reverse entire string =>yob doog a ma I 
Stept2: reverse word by word 
 

No comments:

Post a Comment