jeudi 15 octobre 2020

Extracting all words separated by non-alphabetical characters

Given a string such as:

std::string word = "Hello World!it's@.-/sunday";

I want to extract all the words which are separated by non-alphabetical letters stored in a container like a vector, so for this case it would be:

Hello, World, it, s, sunday 

My initial try was to use isalpha() along with an index count to substr() accordingly like so:

std::string word = "Hello World!it's@.-/sunday";
    int count = 0, index = 0; 
    std::string temp;  
    
     for (; count < word.length();count++){
        if (!isalpha(word[count])){
            temp = word.substr(index,count);
            index = count; 
        }
    }

But this does not work as I thought it would as the index does not update fast enough resulting in words mixed with non-alphabetical characters. Is there perhaps a function or a better way to extract said words?

Aucun commentaire:

Enregistrer un commentaire