Aug 30, 2012 at 4:25pm Aug 30, 2012 at 4:25pm UTC
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 Aug 30, 2012 at 4:26pm Aug 30, 2012 at 4:26pm UTC
Aug 30, 2012 at 4:33pm Aug 30, 2012 at 4:33pm UTC
int give_me_the_position_of_the_n_word(const char *s, int n);
Aug 30, 2012 at 5:53pm Aug 30, 2012 at 5:53pm UTC
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 Aug 30, 2012 at 5:55pm Aug 30, 2012 at 5:55pm UTC
Aug 30, 2012 at 6:33pm Aug 30, 2012 at 6:33pm UTC
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 Aug 30, 2012 at 6:34pm Aug 30, 2012 at 6:34pm UTC
Aug 31, 2012 at 1:01am Aug 31, 2012 at 1:01am UTC
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 Aug 31, 2012 at 1:15am Aug 31, 2012 at 1:15am UTC