473,394 Members | 1,737 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Replace a substring with another substring using c

i want to replace a word in given string

e. g

string ---- He is a good man.

in above string i want to replace "good" word with "gentle" so finally

i want to print bellow string :-

He is a gentle man.

plz give c program code without using string function.
Oct 7 '08 #1
13 8307
r035198x
13,262 8TB
Please read the posting guidelines. We won't do your homework and spoon feed you with code. Read some tutorials, try the code and post if you have problems with your code.
Oct 7 '08 #2
Tassos Souris
152 100+
What did you did to give the answer in writing??

First, you searched the sentence to find the word.
Then, if you found the word, then when you were writing the sentence again instead of writing the word it is there you wrote the new word.
Expand|Select|Wrap|Line Numbers
  1. isFound = searchWord( sentence, word_to_be_replaced );
  2.  
  3. if ( isFound ){
  4.    // code to replace
  5. }
  6.  
In the "code to replace" you can do many things...
One algorithm that comes quickly in mind is:

Find how many characters there will be in the new sentence
Allocate space for the new sentence
Copy the old sentence to the new sentence up to the point of the word removed
Copy the new word in the new sentence
Copy to the new sentence the remaining of the old sentence (if any)

Hope i helped,
Tassos Souris
Oct 8 '08 #3
sir
i have read your answer, but i want the complete c program if it is possible.

i have tryed more, but failed.

plz send me complete c program without use of string functions.

thank u

from
abc
Oct 10 '08 #4
Tassos Souris
152 100+
I think it is against the rules to post a complete answer..

Oh, by the way, my previous "algorithm" (god make that one!) is not correct.. is just there to make you think about the solution.. It is not correct because there might be multiple occurrences of one string in one sentence, so then you must do and other things... or just change it a little.. like that "every time the word is found in the sentence..".. smt like that..
Oct 10 '08 #5
plz refer this message....................................
sir

i have tryed and also success in replacing word, but it is too long and i wand to reduce the size if it is possible. plz give me kind information if any correction is necessary. plz check my program as per bellow.

Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2. #include<conio.h>
  3.  
  4. void main()
  5. {
  6.     char s1[23],s2[12],s4[30],s3[12];
  7.     int i,j,flag=0,k,m,n=0;
  8.     clrscr();
  9.     printf("enter sentence :-");
  10.     gets(s1);
  11.     printf("enter word which u wish to replace from above sentence:-");
  12.     gets(s2);
  13.     printf("enter new word which u wish to replace:-");
  14.     gets(s3);
  15.     j=0;
  16.     for(i=0;s1[i];i++)
  17.     {
  18.  
  19.         if(s1[i]==s2[j] && s1[i]!='\0' && s2[j]!='\0')
  20.         {
  21.               j++;
  22.               if(s2[j]=='\0')
  23.               {
  24.  
  25.             for(k=0;s3[k];k++)
  26.             {
  27.                 s4[n]=s3[k];
  28.                 n++;
  29.             }
  30.             s4[n]=' ';
  31.             flag=1;
  32.               }
  33.               continue;
  34.         }
  35.         else
  36.         {
  37.             if(flag==1)
  38.             {
  39.                 s4[n]=s1[i];
  40.                 n++;
  41.             }
  42.             if(flag==0)
  43.             {
  44.                 s4[n]=s1[i];
  45.                 n++;
  46.                 j=0;
  47.             }
  48.  
  49.  
  50.         }
  51.     }
  52.  
  53.     s4[n]='\0';
  54.     printf("s4=%s",s4);
  55.     getch();
  56. }
  57.  
thank u

from
abc
Oct 10 '08 #6
Tassos Souris
152 100+
Use code tags... no-one will read that code as you posted it...
Oct 10 '08 #7
boxfish
469 Expert 256MB
Yes. To use code tags, put [CODE] before the code and [/CODE] after it so it shows up in a box with a monospace font. At least on the browser I am using, IE7, not using code tags wrecks the indentation so the code is almost unreadable.
Oct 10 '08 #8
boxfish
469 Expert 256MB
There are a few things you can do to improve the code that you posted. For example:

I see no reason for the continue statement. If you're at the end of that first if statement, then you're just going to go to the top of the loop anyway, because the rest of the loop is consumed by the else that you won't be visiting.

On this line
if(s1[i]==s2[j] && s1[i]!='\0' && s2[j]!='\0')
I don't see a reason to check whether s1[i]!='\0' because the loop
for(i=0;s1[i];i++)
guarantees that s1[i]!='\0'.

And it would help a lot if you gave your variables more descriptive names. Instead of s1, s2, s3, and s4, call them things like oldPhrase, oldWord, newWord, and newPhrase. Instead of flag, call it something like findingWord. And make it boolean. And so on. And you can improve the code in the else statement.

main should return an int. On some compilers, code in which main does not return an int will not compile. It should return 0;

I think your professor will give you a lot more points if you put some comments in your code that explain how it works.

Hope this helps.
Oct 10 '08 #9
Tassos Souris
152 100+
Here are some tips:

- You have declared a variable called 'm' but you do not use it. This means that you have something wrong or you have forgot something, cause otherwise you wouldn't have included the 'm' variable.

-Supply more buffer for the sentences. Increase the size from 23 to let's say 50... Also, it is not a good idea to make the number of characters for the output array fixes because you do not know how many characters it will eventually have.. the word to replace one word from the sentence might be very big and even worse it might be replaced in many places.

- Change the numbers 23, 12, ... to #defines:
#define SENTENCE_MAX_LEN 50

-Change names s1, s2, s3... to for example:
char sentence[ SENTENCE_MAX_LEN ];

-Do not ever use gets()!!! Why? Because it does not check how many characters it receives and it might lead to memory leaks. Especially for your program, this is very easy. When you ask for a sentence, i just put a sentence. But most sentences are more than 22 characters... your program does not check this. If you are lucky you will get an assertion or something like that.
You must check the number of characters you receive to store them in the array. You use fgets() like this:
fgets( sentence, SENTENCE_MAX_LEN, stdin );
which says read up to one less than SENTENCE_MAX_LEN characters from stdin and store them in sentence. Also, put a '\0' character at the end.

Till that point your program can be restructured like that:
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.  
  3. #define SENTENCE_MAX_LEN 50
  4. #define WORD_MAX_LEN 15
  5.  
  6. int main( void ){
  7.  
  8.    char sentence[ SENTENCE_MAX_LEN ];
  9.    char word[ WORD_MAX_LEN ];
  10.  
  11.     fprintf( stdout, "\nPlease enter one sentence. Note that i will accept only
  12.                                    %d characters!\n", SENTENCE_MAX_LEN - 1 );
  13.     fflush( stdout );
  14.     fgets( sentence, SENTENCE_MAX_LEN, stdin );
  15.     /* you might also want to get rid of unwanted-extra input here... */
  16.  
  17.     fprintf( stdout, "\nNow give me the word you want me to replace. Note that i
  18.                                    will accept only %d characters!\n", 
  19.                                    WORD_MAX_LEN - 1 );
  20.     fflush( stdout );
  21.     fgets( word, WORD_MAX_LEN, stdin );
  22.     /* you might also want to get rid of unwanted-extra input here... */
  23.  
  24.     ....
  25.  
  26.     return ( 0 );
  27.  
  28. }
  29.  
- Do not put everything in a big for loop. This is not the purpose of structural programming. Divide this thing in small routines that you can check, debug, modify and extend easily. What you must do is:
Find what does each section of your for loop accomplishes.
Make each task to a separate routine.


-Your for loop will execute meaninglessly even if the word in not found in the sentence. Check for that too.

To continue from above you can do:
Expand|Select|Wrap|Line Numbers
  1.      fprintf( stdout, "\nI am searching for the word \"%s\" you want me to   replace...\n", word );
  2.  
  3.      occurrences = searchWord( sentence, word );
  4.  
  5.     if ( occurences > 0 ){
  6.            fprintf( stdout, "\nI found the word %s %d times in the sentence.\n",
  7.                             word, occurrences );
  8.  
  9.            replaceWord( sentence, word );
  10.  
  11.     }
  12.     else{
  13.  
  14.       fprintf( stdout, "\nSorry but i did not found the word in the sentence... Goodbye!%c", '\n' );
  15.          return ( 1 );
  16.  
  17.     }
  18.  
-When you output, you say: s4=%s.
This is really, really bad. What the hell is s4??? How the hell will a user running the program know what s4 is? He does not know how you name your variables!!! Probably he does not know that behind the program there is source code!!!!!!!!!!!!
Make a friendly user interface. Put nice messages, like:
For input:
Type some text. I will only receive %d characters!
Please enter the word you want me to locale in the sentence and replace it with another word.
The word is not located in the sentence. Please enter again.
There are %d occurrences of the word in the sentence. Enter the word that you want to replace word %s.
For output:
The sentence with the word(s) replaced is: %s. ---> you do this like that:
Expand|Select|Wrap|Line Numbers
  1. fprintf( stdout, "\nThe sentence with the %s replaced is: %s\n", 
  2.                                                    occurrences == 1 ? "word" : "words", 
  3.                                                    newSentence );
  4.  
Personally, i suggest that you divide in its own routine even the part (in the code above i show you) that reads input. Assign the correct responsibilities to each of the routines.

Let us know how you progress!!
Oct 10 '08 #10
sir,

a lots thank for kind guideline for good programing code and i also hope u will me give this type of tips always.

thanks again.....

sir i want to ask a question for bellow comments.....
i can't undestand it, plz explain with more detail..


and u suggest to check
On this line
if(s1[i]==s2[j] && s1[i]!='\0' && s2[j]!='\0')
I don't see a reason to check whether s1[i]!='\0' because the loop
for(i=0;s1[i];i++)
guarantees that s1[i]!='\0'.

thank

from
abc mavdi
Oct 11 '08 #11
Tassos Souris
152 100+
sir,

a lots thank for kind guideline for good programing code and i also hope u will me give this type of tips always.

thanks again.....

sir i want to ask a question for bellow comments.....
i can't undestand it, plz explain with more detail..


and u suggest to check
On this line
if(s1[i]==s2[j] && s1[i]!='\0' && s2[j]!='\0')
I don't see a reason to check whether s1[i]!='\0' because the loop
for(i=0;s1[i];i++)
guarantees that s1[i]!='\0'.

thank

from
abc mavdi

your for loop
Expand|Select|Wrap|Line Numbers
  1. for ( i = 0; s1[ i ]; i++ ){
  2.   ...
  3. }
  4.  
does 3 things:
1. Set 0 to 'i'
2. Evaluate the expression s1[ i ].
3 If it is true execute the body of the for loop
4 At the end of the body of the for loop, execute i++
Repeat steps 2-4 until step 2 indicates false evaluation.

So, in simple words your for loop will continue executing until the expression:
Expand|Select|Wrap|Line Numbers
  1. s1[ i ];
  2.  
becomes false.

Well, s1[ i ] will hold a value.. it would be either a character (including spaces), or the terminating null character '\0'.
In the case of characters, evaluating the expression s1[ i ], means returning the character. The for loop then takes the character and sees if it is true or false. You should know that true means not-zero and false zero. Since, a character is nothing more than a small integer (you are working with ASCII characters, ranging from 0 to 255 i think), and it is greater than zero, then the value is true . So, for continues executing the body of the for loop.

When, however you reach the end of the array and encounter '\0', its value is zero. So, it is false and the for loop terminates.

Hope i helped!

With respect,
Tassos Souris
Oct 11 '08 #12
sir

i have read ur.

but one problem is remaining which i explain in bellow :-

in a sentence like :- "i live in india"

word like :-"india"

replace word is:-"bharat"

then i will find output as per bellow :

output:-" lve bharat"

but i want to replace only "india" word whatever time it occurs in a sentence.

thanks

from
abc
Oct 11 '08 #13
Tassos Souris
152 100+
It seems that there is a serious problem in your code...
In Visual Studio 2008 sometimes it crashes, sometimes it continues execution with wrong results.... This means that you do something wrong..

What you must do is:
EXECUTE your code MENTALLY in a white paper... Write with a pencil all the variables and see how your code executes.. does it executes as you expect? If not, since you are keeping track of all the variables in the paper, you can figure out what goes wrong...

You can use tools to assist you. There seems to be a memory problem there.. with all these arrays.. you probably write past the boundaries of an array...
Use "Memory Profilers"... you can find many of them which are free (Open Source) for linux.. there are some for windows too...You can use a program called "lint" that checks C programs for common errors... You can use the debugger (get used to it!!!!!!!!!!!)......
You must learn how to use these tools... most importantly you must learn how to use these tools to find and solve bugs in your code.. like the one you are having now...

Do the above and let us know the results...
Oct 11 '08 #14

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: tmaster | last post by:
Within a class, can I create a property that is a listview? Here's what I tried, but it doesn't seem to work: '------------ create property to give the second form access to the first form's...
4
by: system55 | last post by:
I need some help.... How can i create a program wherein it can copy a file about 2MB in size, into another file using the extended memory allocation??? Do i need to use some interrupt calls in dos??
1
by: vikas chand | last post by:
I have this project in which I have to transfer a .JPG file size(4-8 KB) through serial port to another PC using Visual C++(preferred). You can also help is you have something in Turbo c also.
1
by: dean.brunne | last post by:
Hi, How can I run a macro stored in another database using code?? I figure it would be something like: Dim db as Database Set db = ?????
1
by: yasinirshad | last post by:
HI, Can anyone tel me How to copy data from a table in one database to a table in another database using sqlserver2005. Thanks in advance.
4
by: Npreeti | last post by:
HI , I want to copy a file from one machine to another machine using perl. Also i want to know whether i can past arguments to perl program?
0
by: anureddy | last post by:
help me how to add datagridview columns to another table,using windowsapplications. and set the displaymember and value member datagridviewcomboboxcolumn. i used this below code but that not...
10
by: Debajit Adhikary | last post by:
I have two lists: a = b = What I'd like to do is append all of the elements of b at the end of a, so that a looks like: a =
1
by: gopim | last post by:
gridview inside another gridview using Asp.net C#
5
by: sreenu123 | last post by:
Hi, I want to read from values from database and add to listbox then transfering items from one listbox to another listbox using C#.NET. Can any one give source code. Thanks in advance sree
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.