-4

how do i divide a sentences in c++ like :

input from cin (He said, "that's not a good idea". )

into

He

Said

That

s

not

a

good

idea

to test whether a character is a letter, use a statement (ch >='a' && ch <='z') || (ch >='A' && ch <='Z').

Community
  • 1
  • 1
  • https://stackoverflow.com/questions/236129/the-most-elegant-way-to-iterate-the-words – Sv Sv Nov 05 '17 at 10:38
  • 2
    What have you tried? You can't (and shouldn't) get the homework done here. – bolov Nov 05 '17 at 10:41
  • You probably *could* use a regular expression. You *could* write a proper parser with a grammar, you *could* probably just split the string by a few specific characters. There are *many* options. – Jesper Juhl Nov 05 '17 at 12:27

1 Answers1

0

You can split string by spaces then check each word if it has any characters other than A-z or not. if it has, erase it. Here's a tip :

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
std::vector<std::string> splitBySpace(std::string input);
std::vector<std::string> checker(std::vector<std::string> rawVector);

int main() {
    //input
    std::string input ("Hi, My nam'e is (something)");
    std::vector<std::string> result = checker(splitBySpace(input));

    return 0;
}

//functin to split string by space (the words)
std::vector<std::string> splitBySpace(std::string input) {
    std::stringstream ss(input);
    std::vector<std::string> elems;

    while (ss >> input) {
        elems.push_back(input);
    }

    return elems;
}

//function to check each word if it has any char other than A-z characters
std::vector<std::string> checker(std::vector<std::string> rawVector) {
    std::vector<std::string> outputVector;
    for (auto iter = rawVector.begin(); iter != rawVector.end(); ++iter) {
        std::string temp = *iter;
        int index = 0;
        while (index < temp.size()) {
            if ((temp[index] < 'A' || temp[index] > 'Z') && (temp[index] < 'a' || temp[index] > 'z')) {
                temp.erase(index, 1);
            }
            ++index;
        }
        outputVector.push_back(temp);
    }
    return outputVector;
}

in this example result is a vector that has words of this sentence.

NOTE : use std::vector<std::string>::iterator iter instead of auto iter if you are not using c++1z

HMD
  • 2,202
  • 6
  • 24
  • 37