473,419 Members | 1,717 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,419 software developers and data experts.

need help! replacing substing in a string with another substring

I am trying to expand on a earlier program for counting subs and now i am trying to replace substrings within a given string. For example if the main string was "The cat in the hat" i am trying to find a chosen substring lets say "cat" and then replace it with a difrent inputed substring say "dog". Tried to get as far as i could on my own but need some help, sugestions, snippets or guidence.

Expand|Select|Wrap|Line Numbers
  1. # include<stdio.h>  
  2. # include<math.h>
  3. # include<stdlib.h>
  4. # include<string.h>
  5.  
  6. int main(void)
  7.  
  8. {
  9.  
  10. char s[200], old[75], new[25];
  11. char newstr[200];
  12. char *newtsr=NULL;
  13.  
  14. char count;
  15. int count2;
  16. int run;
  17. int i;
  18. int j;
  19. int strstrcnt(const char *s,const char *old);
  20. char *replace(const char *s, const char *old, const char *new);    
  21. printf("\nThis is a program to find certian occurances of words in a user inputed sentence\n");
  22. printf("\nIt will display the number of times the word is found.\n");
  23.  
  24. printf("\nTo run this program and input the word to find and the sentence to search hit 1,\n\n Hit 2 to exit.\n");
  25. printf("\nHit 4 to find a word then replace it/n");
  26. scanf("%d",&run);
  27.  
  28. fflush(stdin);
  29.  
  30. while (run==1)
  31.  
  32. {printf("\nPlease input the sentence you wish to hae searched.\n");
  33.  
  34.  gets(s);
  35.  
  36.  printf("\nPlease enter the word or term you wish to have found in the sentence.\n");
  37.  
  38.  gets(old);
  39.  
  40.  fflush(stdin);
  41.  
  42.  count=strstrcnt(s,old);
  43.  
  44.  printf("There is %d instances of the selected word in the sentence.\n\n %s\n\n",count,s);
  45.  printf("Hit 2 to exit 1 to continue, Hit 3 to ignore case sensitivity.Hit 4 to replace the word.\n\n");
  46.  fflush(stdin);
  47.  scanf("%d",&run);
  48.  
  49.  
  50. while (run==3)
  51. {  strupr(s)newstr = replace(s,new,old);;
  52.    strupr(old);
  53.    count=strstrcnt(s,old);
  54.  
  55.  
  56.  printf("There is %d instances of the selected word in the sentence.\n\n %s\n\n",count,s);
  57.  printf("Hit 2 to exit, 1 to continue, 3 to run non case sensitive again.\n\n");
  58.  fflush(stdin);
  59.  scanf("%d",&run);
  60.  
  61.                   }
  62. while (run==4)
  63. {printf("\n Please enter the new string to replace the old words\n");
  64.  
  65.     scanf("%s",&new);
  66.     fflush(stdin);
  67.    newstr = replace(s,new,old);
  68.    printf("%s",newstr);
  69.    printf("\nPlease hit 1 to continue\n");
  70.    scanf("%d",&run);
  71.    fflush(stdin);
  72. }}
  73. return(0);}newstr = replace(s,new,old);
  74.  
  75. int strstrcnt(const char *s,const char *old)
  76. {  int i;
  77.    char *q;//pointer
  78.    int count=0;
  79. int length=strlen(old); 
  80.    for (i=0;i<length;i++)
  81.    q=strstr(s,old);
  82.    while (q!= NULL)
  83.    {q=strstr(q+1,old);
  84.        count++;}//counter
  85.  
  86. return count;}
  87.  
  88. char *replace(const char *s, const char *old, const char *new)
  89. {
  90. char *ret, *sr;
  91. size_t i, count = 0;
  92. size_t newlen = strlen(new);
  93. size_t oldlen = strlen(old);
  94.  
  95. if (newlen != oldlen) {
  96. for (i = 0; s[i] != '\0'; ) {
  97. if (memcmp(&s[i], old, oldlen) == 0)
  98. count++, i += oldlen;
  99. else
  100. i++;
  101. }
  102. } else
  103. i = strlen(s);
  104.  
  105. ret = malloc(i + 1 + count * (newlen - oldlen));
  106. if (ret == NULL)
  107. return NULL;
  108.  
  109. sr = ret;
  110. while (*s) {
  111. if (memcmp(s, old, oldlen) == 0) {
  112. memcpy(sr, new, newlen);
  113. sr += newlen;
  114. s += oldlen;
  115. } else
  116. *sr++ = *s++;
  117. }
  118. *sr = '\0';
  119.  
  120. return ret;
  121. }
  122.  
  123.  
has two errors when compiling and crashes if ran
the errors are
|75 error 8004| 'newtsr' is assigned a value that is never used in function main
|69 error 2277| Lvalue required in function main

NOTE: This is me trying to better understand C and explore what it can do.
Apr 2 '08 #1
4 2778
gpraghuram
1,275 Expert 1GB
I havent looked into the code fully.
But what logic r u using in the replace function.
Logic should be
1)You should know the position where u are going to replace
2)From position 0 to the matched position copy original string
3)Form matched position copy the replace string
4)From the last copied position copy the remaining original string

take care you allocate enough memory for the final string

Raghuram
Apr 3 '08 #2
mmk
19
I havent looked into the code fully.
But what logic r u using in the replace function.
Logic should be
1)You should know the position where u are going to replace
2)From position 0 to the matched position copy original string
3)Form matched position copy the replace string
4)From the last copied position copy the remaining original string

take care you allocate enough memory for the final string

Raghuram
Even I have gon through the logic but its totally messed but. Anyway what Raghu suggest is great approach.

One more approach can be.

I assume the input string is a single line.

Data structures required : newstr,tempstr,searchstring,oldstr of string type

1. Read line into "oldstr".
2. Read the string to change into "serachstring".
3. Now traverse from postion 0 to \n in oldstr searching for "searchstring". while traversing copy the contents traversed to tempstr.
4. If first character of any string matches. Use strcmp to compare searchstring and foundstring (from pointer position in old str till \0).
5. Based on strcmp return value, if string found, append searchstring to newstr and copy the rest oldstr string to newstr till oldstr \n is reached.

oldstr = "the cast is in hat"
searchstring = "dog"
output : newstr = "the dog is in hat"

Raghu please correct me if i am wrong.
There are various approaches to do this.If we are good at string operations basics this will be easy approach to complete the above assignment.
Apr 3 '08 #3
mmk
19
Even I have gon through the logic but its totally messed but. Anyway what Raghu suggest is great approach.

One more approach can be.

I assume the input string is a single line.

Data structures required : newstr,tempstr,searchstring,oldstr of string type

1. Read line into "oldstr".
2. Read the string to change into "serachstring".
3. Now traverse from postion 0 to \n in oldstr searching for "searchstring". while traversing copy the contents traversed to tempstr.
4. If first character of any string matches. Use strcmp to compare searchstring and foundstring (from pointer position in old str till \0).
5. Based on strcmp return value, if string found, append searchstring to newstr and copy the rest oldstr string to newstr till oldstr \n is reached.

oldstr = "the cast is in hat"
searchstring = "dog"
output : newstr = "the dog is in hat"

Raghu please correct me if i am wrong.
There are various approaches to do this.If we are good at string operations basics this will be easy approach to complete the above assignment.
Sorry i forgot "string to replace" in data structure and in logic . Here modified algorithm

Data structures required : newstr,tempstr,searchstring,replacestr,oldstr of string type

1. Read line into "oldstr".
2. Read the string to change into "serachstring".
3. Now traverse from postion 0 to \n in oldstr searching for "searchstring". while traversing copy the contents traversed to tempstr.
4. If first character of any string matches. Use strcmp to compare searchstring and foundstring (from pointer position in old str till \0).
5. Based on strcmp return value, if string found, append replacestr to newstr and copy the rest oldstr string to newstr till oldstr \n is reached.

oldstr = "the cast is in hat"
searchstring = "dog"
output : newstr = "the dog is in hat"
Apr 3 '08 #4
mmk
19
Sorry i forgot "string to replace" in data structure and in logic . Here modified algorithm

Data structures required : newstr,tempstr,searchstring,replacestr,oldstr of string type

1. Read line into "oldstr".
2. Read the string to change into "serachstring".
3. Now traverse from postion 0 to \n in oldstr searching for "searchstring". while traversing copy the contents traversed to tempstr.
4. If first character of any string matches. Use strcmp to compare searchstring and foundstring (from pointer position in old str till \0).
5. Based on strcmp return value, if string found, append replacestr to newstr and copy the rest oldstr string to newstr till oldstr \n is reached.

oldstr = "the cast is in hat"
searchstring = "dog"
output : newstr = "the dog is in hat"

Sorry i forgot "string to replace" in data structure and in logic . Here modified algorithm

Data structures required : newstr,tempstr,searchstring,replacestr,oldstr of string type

1. Read line into "oldstr".
2. Read the string to change into "serachstring".
3. Now traverse from postion 0 to \n in oldstr searching for "searchstring". while traversing copy the contents traversed to tempstr.
4. If first character of any string matches. Use strcmp to compare searchstring and foundstring (from pointer position in old str till \0).
5. Based on strcmp return value, if string found, append replacestr to newstr and copy the rest oldstr string to newstr till oldstr \n is reached.

oldstr = "the cast is in hat"
searchstring = "dog"
output : newstr = "the dog is in hat"
Apr 3 '08 #5

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

Similar topics

6
by: mike | last post by:
Hello, After trying to validate this page for a couple of days now I was wondering if someone might be able to help me out. Below is a list of snippets where I am having the errors. 1. Line 334,...
5
by: John Flynn | last post by:
hi all i'm going to be quick i have an assignment due which i have no idea how to do. i work full time so i dont have the time to learn it and its due date has crept up on me .. As follows:...
0
by: xunling | last post by:
i have a question about answering ..... this topic is "need help" what do i have to write at te topic line, !after i have klicked the "answer message" button ive tried many possibilities,...
4
by: Scott Holland | last post by:
HELP - Need to connect to DB2 database on AIX from NT server. Also AS/400 from NT Server -- I am experienced in ORACLE and a novice at DB2. What tools would be the equivalent of Net*8 or...
7
by: Timothy Shih | last post by:
Hi, I am trying to figure out how to use unmanaged code using P/Invoke. I wrote a simple function which takes in 2 buffers (one a byte buffer, one a char buffer) and copies the contents of the byte...
1
by: MSDN Account | last post by:
We have web site that used the IIS ResKit tool MSWC.PermissionChecker to check file permissions. The web site has been upgraded and that upgrade included changing the default server side language...
10
by: L. R. Du Broff | last post by:
I own a small business. Need to track a few hundred pieces of rental equipment that can be in any of a few dozen locations. I'm an old-time C language programmer (UNIX environment). If the only...
23
by: vinod.bhavnani | last post by:
Hello all, I need desperate help Here is the problem: My problem today is with multidimensional arrays. Lets say i have an array A this is a 4 dimensional static array.
7
by: themastertaylor | last post by:
Hi, I work for a construction company and part of my job is sourcing materials. currently we have a spreadsheet based system whereby each site has a worksheet in the workbook with the standard...
1
by: jhaydon | last post by:
First of all, I'm not a CSS expert. If I was, I wouldn't need to be posting for help here. Secondly, I have been doing web design for several years, just not css. Thirdly, I need help and hope...
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
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

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.