954,506 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

help on string

I need to let the user input a line of words and make all the 4 letter words in the sentence "love"....

example:
cin>> I hate programming

output --> I love programming


does anybody know if there is any library, or string member functions would help doing this task?

below is so far what i have, i have a function to return the index of the space... I don't know what else i can do.

# include <iostream>
# include <string>
using namespace std;
int indexCounter(string sentence, int startingIndex);

int main()
{
	string line;
	int startIndex=0;
	int endIndex=0;
	int size= line.size();
	
	cout<<"Please enter a sentence."<<endl;
	getline(cin,line);




	return 0;
}



int indexCounter(string sentence, int startIndex, int& endIndex)
{
	for(int i=startingIndex; i<size; i++)
	{
		if(sentence[i]==' ')
		{
			return i;  //white space index
		}
		endIndex=i;
		
	}
}
k2k
Posting Whiz
352 posts since Nov 2007
Reputation Points: 15
Solved Threads: 1
 

How about if you create a function that takes a large string (i.e. the user inputted sentence string named "line") and returns a vector of smaller strings? Each string in the vector would be a word. Something like this:

vector <string> ParseIntoWords (string sentence);


So in your example, you pass this function the string "I hate programming" and it returns a vector of three strings:

I
hate
programming

The function you have could help parse out the separate words, as could the function "isspace" from the cctype library: http://www.cplusplus.com/reference/clibrary/cctype/isspace.html

Also potentially useful could be this function:
http://www.cplusplus.com/reference/string/string/substr.html

You could then go through this vector of strings and check to see whether a string had four letters. If so, change the string. You end up with a vector like this:
I
love
programming

Concatenate the above vector of strings and you have your revised string (except from the period. Also you may have to put the spaces back in).

VernonDozier
Posting Expert
5,527 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 711
 

Use .find() to find the spaces. If you find 2 spaces with 4 characters between them, use .replace() to replace the 4 characters.

And remember, the end of the sentence may not end in a space, but it may end in a 4-letter word.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You