How to replace a string with another string while given the number of word and not position?



Hello ,

I am trying to do a program in which the output should be :


Please enter a string : Hello This is srikanth.
Please enter another string : Rajesh.
Please enter position : 4

The Result : Hello This is Rajesh.

I have tried to do this program in c, using char arrays :


#include <iostream>
#include <stdio.h>

using namespace std;

int main()
{

char ch1[20];
char ch2[20];
int n;

int space_count = 0;

int num_words = 0;

int word_array[10];

int num = 0;


cout<<"Enter something:";
gets(ch1);

int length1 = strlen(ch1);


cout<<"You have Entered:";
puts(ch1);

cout<<"Now Enter Something:";
gets(ch2);

int length2 = strlen(ch2);

for(int i = 0;i<length1;i++)
{
if(ch1[i] == 'a')
{
word_array[++num] = i;
}
}






cout<<"Enter a number to replace :";
cin>>n;

int ch2_n = 0;
//copy
for(int i = word_array[n];i <= length2;i++)
{
ch1[i] = ch2[ch2_n++];
}



puts(ch1);


return 0;
}


Although this program doesn't work that's the work , I have done , I have gone through the strcpy(),strncpy() but they weren't helpful since we enter the word number to replace and not the position of the character.

I think there can be a better solution using strings.
Last edited on
int give_me_the_position_of_the_n_word(const char *s, int n);
If to use the C++ then the task is being done with using std::istringstream and .string method replace as for example

s.replace( s.find( source ), source.size(), target );

As for me I have gotten the following result::)

Please enter a string : Hello This is srikanth
Please enter another string : Rajesh
Please enter position : 4
Hello This is Rajesh
Last edited on

@ne555


1
2
3
4
int give_me_the_position_of_the_n_word(const char *s, int n)
{
   return ( Here_you_are );
}
Last edited on

You have misunderstood my question , I have said I will enter the position of the word not the word that we have to replace with.

Please enter a string : Hello This is srikanth
Please enter another string : Rajesh
Please enter position : 4
Hello This is Rajesh

we don't give the index value where to replace and also which word to replace,
we just give the position of the word.
Last edited on
@srikanth chitturi


Are you saying me? I have understood the task very well. But at first you should to determine the word that has the given successive number in the statement should not you? You can do this by using std::istringstream
Topic archived. No new replies allowed.