2 Replies - 644 Views - Last Post: 20 March 2013 - 10:42 AM Rate Topic: -----

#1 qqaa007  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 30-January 13

[Question] Replace substring

Posted 20 March 2013 - 06:13 AM

Hi,

I have this code here:

#include <stdio.h>


int isSubstring (char s[], char t[])
{
int i, j, k, pos;
pos = -1;
for (i = 0; s[i] != '\0'; i++)
{
for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)
;
if (k > 0 && t[k] == '\0')
pos = i;
}
return pos;
}

int main()
{
char s[] = "All work and no play makes Jack a dull boy.";
char t[5];
char name;

printf("Name to substitute: ");
scanf("%s",&t);

/*Here - This bit not sure what to put*/
name = isSubstring (s, "Jack" , t);

printf("%s %s",name );
/*To here*/

system("pause");
}


I wnat to substitutes the text Jack in the string variable quote with the content of the variable name.

like this;

Name to substitute: Mark
	All work and no play makes Mark a dull boy



I don't what to put there so can i get help
thank you

Is This A Good Question/Topic? 0
  • +

Replies To: [Question] Replace substring

#2 jimblumberg  Icon User is offline

  • member icon


Reputation: 3987
  • View blog
  • Posts: 12,300
  • Joined: 25-December 09

Re: [Question] Replace substring

Posted 20 March 2013 - 06:52 AM

First find an indentation style you like and use it consistently. The way your code is now formatted makes it hard to read.

As to the actual problem, you may want to investigate the strstr() function.


Jim
Was This Post Helpful? 1
  • +
  • -

#3 Adak  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 331
  • View blog
  • Posts: 1,168
  • Joined: 01-April 11

Re: [Question] Replace substring

Posted 20 March 2013 - 10:42 AM

Try to avoid working with individual chars in this job. You want to:

1) use strstr() to find the first letter of "Jack". Everything past the J in Jack, is the "tail". Move it to another array. The first part of the substring "All work and no play makes ", is the "head" part.

2) strcat() "Mark" onto the end of the "head" part substring: "All work and no play makes Mark"

3) now count over "Jack", from the tail, by using it's strlen(). You can use an index or a pointer to count up the needed four chars.

4) now strcat() this part ONLY of the tail, back onto the rest of the head portion.

Since Mark and Jack both have four letters in them, you can do this in a simpler way, but I'm not describing it because it fails anytime you have to work with Michael and Jack, or Laurel and Jack - anything that has an unequal number of chars in it.

Need I mention that string.h is required for this - no - I think not.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1