473,225 Members | 1,311 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,225 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 2763
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...
1
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
0
by: veera ravala | last post by:
ServiceNow is a powerful cloud-based platform that offers a wide range of services to help organizations manage their workflows, operations, and IT services more efficiently. At its core, ServiceNow...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
0
by: mar23 | last post by:
Here's the situation. I have a form called frmDiceInventory with subform called subfrmDice. The subform's control source is linked to a query called qryDiceInventory. I've been trying to pick up the...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...

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.