HCL America Interview Question
Software Engineer / DevelopersThe above is way too complicate - using strstr makes it a lot easier:
void remsub(char* str, const char* pattern)
{
char* loc = NULL;
int len_pat = strlen(pattern);
while(loc = strstr(str, pattern)) {
strcpy(loc, loc+len_pat);
}
}
int main()
{
char val[] = "Hello, xyyddccyydcc";
const char* pattern = "yd";
remsub(val, pattern);
printf("%s\n",val);
return 0;
}
This gives you:
Hello, xccycc
Here In While loop there is no change in Pattern and str so when while loop will going to stop
can u plz explain the login behind this
@Dnyaneshwar, the pattern doesn't change (and shouldn't). The string is changed by the strcpy in the while loop -- 'loc' points to the beginning of the pattern within the original string.
While I agree that the strstr solution is a lot simpler than the preceding one, it is not a recursive one as required. Here is a recursive (and slower) version:
// recursive version
void remsub(char* str, const char* pattern)
{
char* loc = strstr(str, pattern);
if (!loc)
return str;
else {
strcpy(loc, loc+strlen(pattern));
return remsub(str, pattern);
}
}
to Dnyaneshar: if you add one line to the code and check the output, you will understand
it better.
void remsub(char* str, const char* pattern)
{
char* loc = NULL;
int len_pat = strlen(pattern);
while(loc = strstr(str, pattern)) {
puts(loc);
strcpy(loc, loc+len_pat);
}
}
int main()
{
char val[] = "Hello, xyyddccyydcc";
const char* pattern = "yd";
remsub(val, pattern);
printf("%s\n",val);
return 0;
}
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
char *rmv(char *src,const char *ptr){
char *first;
first=strstr(src,ptr);
if(!first)
return src;
else{
cout<<first<<endl;
strcpy(first,first+strlen(ptr));
rmv(src,ptr);
}
return src;
}
int main(){
char s[]="aabbccddccddcc";
const char *p="cc";
char *t;
t=rmv(s,p);
cout<<t;
getchar();
return 0;
}
char* substrrecursion(char* str, char*s)//str is the string and s is the substring
- matrix September 26, 2009{ int k=0,i=0,j=0,m=0,t=0;
char* str1;
for(i=0;i<strlen(str);i++)
{if(str[i]==s[k]){
t++;
for(int j=1;j<strlen(s);j++)
{if(str[i+j]==str[++k]){m++
continue;}
else
break;
}
}}
if(m==strlen(s)-1)
{
for(j=0,k=0;k<strlen(str);j++){
if(j!=i){
str1[j]=str[k];
k++;
}
else(k=i+strlen(s))
}}
substrrecursion(str1,s);
}
else{ return str1;
}
}