Sunday 31 July 2016

dealing with substrings !

Hello friends !
Here are some pieces of codes which deal with "substrings",
  • retrieving the position of substring
  • replacing the substring.

//retrieving the position of substring in main string.

#include<stdio.h>
void replace(char *a,char *rep,int p);
int substring();
void main()
{
char str[50],sub[50],rep[50];
int position;
printf("Enter string:\n");
gets(str);
printf("Enter substring :\n");
gets(sub);
position=substring(str,sub);
printf("The starting point of substring is :\t%d\n",position);
printf("Enter the new substring :\n");
gets(rep);
replace(str,rep,position);
}

// for position
int substring(char *a,char *sub)
{
int i=0,j=0;

while(a[i]!='\0')// checking each character of string
{
    if(a[i]==sub[0])// if any character matches the initial of substring
    {    j=1;        // we need to check all character matches or not
        while(sub[j]!='\0' && a[i+j]!='\0' && a[i+j]==sub[j] )
        {
            j++;// iff all charater matches , means this is the required substring
                // it will run every time.
        }
    }
    if(sub[j]=='\0')// in matching case only , this "if" condition is satisfied
        return i+1;
i++;
}

return 0;
}

// function for replacing the given string
// works for same length substring only

void replace(char *a,char *rep,int p)
{
int i,j;
for(i= p-1,j=0;rep[j] != '\0';i++,j++)
{
    a[i]=rep[j];
}
printf("The new string is :\n%s\n",a);
}



Thanking you !

No comments :

Post a Comment