string manipulation

hey guys i need help with my code ; well I am required to write a program that uses getline to read a string, counts the number of occurrences of the substring “is” in this string, and replaces all occurrences of “is” by “at” . I've written the code but there seems to be an error in replacing "is" and "it".



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
  #include <iostream>
#include <string>
using namespace std;

int main() {

	int length=0, position=0;
	int counter=1;
	
	string statement ;
	string string1 = " is ";
	string string2 = " at ";
	
	cout << " Enter a statement : " << endl;
	getline(cin , statement);

	length = statement.length();
	position = statement.find(string1);

	while ( position != string::npos ) {
		for ( int i = 0 ; i < string2.length() ; i++) {
		
			statement.replace(position, string1.length() , string2 ); 
		}
		counter++;
		
		
			
		position = statement.find( string1 , position + string1.length() );
		
	}
	

	cout << "The number of occurance of \"is\" is :" << counter << endl;
	
	cout << "The new statement after being altered is : " << statement << endl;

	system ("pause");
	
	return 0;
}
First of all why was counter initialized by 1?

The main loop is simple

1
2
3
4
5
6
7
8
size_t counter = 0;
std::string::size_type n = 0;

while ( ( n = statement.find( string1, n ) ) != std::string::npos )
{
	statement.replace( n, string1.size(), string2 );
	counter++;
}
thnx it worked well, but is it possible that you could tell where the my code failed; would appreciate it.
Except that your code is silly, for example what does this loop do? }

1
2
3
		for ( int i = 0 ; i < string2.length() ; i++) {
		
			statement.replace(position, string1.length() , string2 ); 
}

I see the only reason that you skip the trailing balnk. For example for this statement

" is is "


your code will not work because it will not find the second
" is "
Last edited on
Topic archived. No new replies allowed.