Q.Write a function to accept a main string, one search string and one replace string. Replace the first occurence of search string in main string by replace string{assume the length of search and replace string is same).

Solution I tried

#include<stdio.h>
#include<conio.h>
void main()
{
char mai[80],search[40],replace[40];
int i,j,k,l;
printf("Enter main string\n");
gets(mai);
printf("Enter search string\n");
gets(search);
printf("Enter replace string(same len as search)\n");
gets(replace);
for(i=0;mai!='\0',search!='\0';i++)
 {
 if(mai[i]==search[0])
         {
  for(j=i+1,k=1,l=0;mai!='\0',search!='\0',replace!='\0';j++,k++,l++)
   {
   if(mai[j]==search[k])
    {
    mai[j-1]=replace[l];
    }
   }
  }
 }
printf("New string is %s\n",mai);
}

I am not gettin the desired output. And what does it mean by first occurence of search string? Does it mean the whole string or first letter of search string? HELP!!:confused: :sad:

You are better off dumping gets which will save you a lot of trouble in the future.

Look into functions like strstr to ease your task.

Oh, and btw, main returns in int.

You are better off dumping gets which will save you a lot of trouble in the future.

Look into functions like strstr to ease your task.

Oh, and btw, main returns in int.

Thnx for the suggestions.That function would do just fine but I have to do it without using pre defined fucntions or methods. Was what I did even remotely right???

I am not gettin the desired output. And what does it mean by first occurence of search string? Does it mean the whole string or first letter of search string? HELP!!:confused: :sad:

It means whole string of search string...

For example:

Input : I Have This Book
Search : ve
Replace : te

Output : I Hate This Book

I looked at your code but didn't trace it well.You catched something but you're assigning the search chars wrong place at somewhere...
The best way to understand the wrong which you're doing is tracing your program on a paper.Therefore you can show the logical errors easiliy...

If you want another solution, you can examine this code which is below.But not forget it : Your solution is better than the others for learning...

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

 
int replaceStr(char str[], char search[], char replace[]);

int main()
{
    char string[50],search[20],replace[20];
    int a;
  
    
    printf("Enter the string\n");
    gets(string);
    
    printf("Enter the searching string\n");
    gets(search);
    
    printf("Enter the replace string\n");
    gets(replace);
    
    a = replaceStr(string,search,replace);
    
    if(a != 1)
    puts(string);
    

    getch();
    
    return 0;
    
}

int replaceStr(char str[], char search[], char replace[])
{
    
    int count = 0,k;
    int start;
    
    int i = 0;
    
  
                    
             for(k = 0; k < strlen(search); k++)
             {
                   if(str[i] == search[k])
                   {
                             if(count == 0)
                             start = i;
                   count++;
                   i++;
                   
                   }
                   
                   else
                   {
                       count = 0;
                       i++;
                       k = - 1;
                       
                       
                       
                       
                       if(i == strlen(str)){
                       printf("Not found\n");
                       return 1;
                       }
                       
                   }
                   
                   
                   
             }
             
             
             if(count != 0)
             i = start;
             else
             return 0;
             
            
             if(count == strlen(search))
             {
                      
                      
                      for(k = 0; replace[k] != '\0'; k++,i++)
                      {
                            str[i] = replace[k];
                      }
                      
             }  
             
            
  
    
    return 0;
    
}
#include<conio.h>

I don't see any reason for you to use this header file in your code.
In fact try to avoid using it at all, since is compiler specific and will make your code not portable.

@FoX_: Read what ~s.o.s~ posted. Using gets() is a bad idea. Here's another link which proves its uselessness:
http://www.cprogramming.com/faq/cgi-bin/smartfaq.cgi?answer=1049157810&id=1043284351

Your searching function has its flaws, too. I won't say I know better than this, because in the other thread I recommended this solution, trying to save iterations. :rolleyes: If you have any doubts about why it shouldn't be 2 nested loops, try the following data to search:

the string = "Beginning"
searching string = "ning"
replacing string = "www"

>I don't see any reason for you to use this header file in your code.
It's because getch() is used, and should be replaced by getchar(), as all we're using it for is pausing the program.

It's because getch() is used, and should be replaced by getchar(), as all we're using it for is pausing the program.

I was talking about the original poster. And there's not reason to use
that header file there.

I don't see any reason for you to use this header file in your code.
In fact try to avoid using it at all, since is compiler specific and will make your code not portable.

Yes I know this isn't a standart C header. I wrote it because I accustomed it.(I know tihs is a bad habit)

Including the standart header <stdlib.h> and putting system("pause"); before return 0; can be a solution or using getchar(); can be a solution too...

@FoX_: Read what ~s.o.s~ posted. Using gets() is a bad idea. Here's another link which proves its uselessness:
http://www.cprogramming.com/faq/cgi-bin/smartfaq.cgi?answer=1049157810&id=1043284351

Your searching function has its flaws, too. I won't say I know better than this, because in the other thread I recommended this solution, trying to save iterations. :rolleyes: If you have any doubts about why it shouldn't be 2 nested loops, try the following data to search:

the string = "Beginning"
searching string = "ning"
replacing string = "www"

>I don't see any reason for you to use this header file in your code.
It's because getch() is used, and should be replaced by getchar(), as all we're using it for is pausing the program.

Thanks to your warning...
I made some additions and I suppose it works right now...

I sent the string to the array character by character instead of gets function and healed the fault which you found...

However if anyone finds a mistake I will be happy if his/her writes here...

Finally please remind that the new line(Enter)(\n) is a character too...

Here is the revised source code:

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


 
int replaceStr(char str[], char search[], char replace[]);

int main()
{
    char string[50],search[10],replace[10];
    int a,count = 0;
    char b;
    int i;
    

    printf("Enter the string\n");
    for(i = 0; i < 49; i++)
    {
          scanf("%c",&string[i]);
          if(string[i] == '\n')
          break;
    }
    
    string[i] = '\0';
    
    do{
              
    if(count == 0){
       printf("Enter the searching string\n");
                     for(i = 0; i < 9; i++)
                     {
                           scanf("%c",&search[i]);
                           if(search[i] == '\n')
                           break;
                     }
    
    search[i] = '\0';
    
   
    // if(i == 9)
    // You've reached the buffer limit.Remain chars will be written in replacing string
   
    
    printf("Enter the replace string\n");
                     for(i = 0; i < 9; i++)
                     {
                           scanf("%c",&replace[i]);
                           if(replace[i] == '\n')
                           break;
          
                     }
    
    replace[i] = '\0';
    
   
    
    
    count++;
    }
    
    else if(count != 0){
    printf("Search and Replace strings must be same length!\nEnter the searching string again\n");
    
                   for(i = 0; i < 9; i++)
                   {
                         scanf("%c",&search[i]);
                         if(search[i] == '\n')
                         break;
                   }
    
    search[i] = '\0';   
    
    printf("Enter the replace string again\n");
    
                  for(i = 0; i < 9; i++)
                  {
                        scanf("%c",&replace[i]);
                        if(replace[i] == '\n')
                        break;
                  }
    
    replace[i] = '\0';
    
    }
    
    }while(strlen(search) != strlen(replace));
    
    
    
    a = replaceStr(string,search,replace);
    
    if(a != 1)
    puts(string);
    

    b = getchar();
    
   
    
    return 0;
    
}

int replaceStr(char str[], char search[], char replace[])
{
    
    int i = 0,count = 0,k;
    int start;
    int a;
    
    
  
                    
             for(k = 0; k < strlen(search); k++)
             {
                  
                   
                   if(str[i] == search[k])
                   {
                             if(count == 0){
                             start = i;
                             }
                   count++;
                   i++;
                   
                   }
                   
                   else
                   {
                       if(count != 0)
                       i --;
                       
                       count = 0;
                       i++;
                       k = - 1;
                       
                       
                       
                       if(i == strlen(str)){
                       printf("Not found\n");
                       return 1;
                       }
                       
                   }
                   
                   
                   
             }
             
             
             if(count != 0)
             i = start;
             else
             return 0;
             
            
             if(count == strlen(search))
             {
                      
                      
                      for(k = 0; replace[k] != '\0'; k++,i++)
                      {
                            str[i] = replace[k];
                      }
                      
             }        
  
    
    return 0;
    
}

Why overcomplicate the search? Besides, modifying loop indicies inside the loop is a bad idea, as it makes bugs far harder to track down. Personally, I'd break this function into 2 smaller ones, one of them being the string search:

(and notice how this is way simpler, I *think* it works)

int searchString(char *string1, char *string2) {
    
    int i;
    bool found = false;
    const int length1 = strlen(string1);
    const int length2 = strlen(string2);
    
    for (i=0; i<length1; i++) {
        
        // simply loop for the length of the second string
        for (int j=0; j < length2; j++) {
            
            // make sure that we're not at the end of the first string,
            // and that the characters match
            if ( (j+i >= length1) || ( string1[j+i] != string2[j] ) ) {
                found = false;
                break;
            }
            found = true; // so far, so good
        }
        
        if (found)
            return i;
    }
    
    return -1;
}

Looks good though I would have used strncmp to make the task more simpler. Just one statement inside the loop and you are good to go.

Looks good though I would have used strncmp to make the task more simpler. Just one statement inside the loop and you are good to go.

Somehow in my mind I imagined that this had to be written from scratch -- or at least could not use strstr or strncmp , so I wrote the whole thing trying to avoid the use of them. :rolleyes: (I think it was because of that other thread, where somebody was trying to implement their own version of strstr for homework. That got me all confused.)

This article has been dead for over six months. Start a new discussion instead.