hope yall are well.
how would i separate each word from a string?
let's say:
string sentence is initialized with "This is a test string."
how would i separate each word and then print them?
i was thinking something like finding the first space then extract that word and then erase it.
i have some code that needs adjustments.
1 2 3 4 5 6 7 8 9 10 11
while (input != ".")
{
word= input.find(" ");
for (i = 0; i < word; f++)
{
cout << input[f];
input.erase(word, input.length); //this is giving me some error.
//also we can't use pointer yet.
}
}
If you've learned to use cin/cout then you've learned how to use a stringstream, the only thing you need to do is create the stringstream with your source string and then use the extraction operator>> to extract the words into some other string.
It is as @jlb said. Most likely, they are not going to teach you the standard library at all besides ones very common ones like vector or string. It is up to you to learn them and utilize them. Unless your professor explicitly states that you aren't able to use something they have not taught, I do not see why not (if they do, I find it very ridiculous that they would do that).
There are many different ways how to do this. Here are some examples on how to do this.
The point of homeworks like this is NOT to master C++ library magic, it is to understand how to manipulate array data.
Use a loop and find the spacea in the string. Every time you find a space, you have found the end of a word. Extract that from between the current index and the last index. Pay special attention to the beginning and end of the string.
Just because you have to print words doesn't mean you have to extract them. You can print the words a character at a time. Here's a solution using a simple state machine. This extracts words from cin, but can be easily modified to extract them from a string.
#include <iostream>
#include <cctype>
int
main()
{
char ch; // current character
bool inWord=false; // was the last character part of a word?
while (std::cin.get(ch)) {
if (std::isalpha(ch)) {
std::cout << ch;
inWord = true; // indicate you're now in a word in case you weren't
} else {
if (inWord) {
// You've reached the end of a word
std::cout << '\n';
inWord = false;
}
}
}
}
The really hard part of this assignment is deciding what's a word. Fiji885 gives a good test case: "There isn't a meeting until 14:30." Is "isn't" a word? What about "14:30?" Since this is the beginner's forum, I wouldn't dwell on the details, except to document in your comments exactly how you define a word.