Theooc
Theooc

Reputation: 31

Initialts algorithm c++11

I'm trying to write a code which prints out an initials of a string. But I have a problem in one case, where those names are with more than one white-space characters.And I came up with an idea to delete those white-spaces characters that aren't necessary and leave only one white space,but I'm not yet confident in strings and could somebody tell me what I should do ?



#include <iostream>
#include <string>
#include <cctype>

std::string initials(const std::string &w )
{
    char space = ' ';
    std::string a;
    a.push_back(w[0]);
    for (int i = 0; i < w.size(); ++i)
    {
        if (w[i] == space )
        {
            a.push_back(w[i+1]);


        }

    }
    return a;
}

int main()
{
    std::cout<<  initials(std::string("Julian     Rodriguez        Antonio "))<<std::endl;

}

Upvotes: 0

Views: 64

Answers (1)

Damien
Damien

Reputation: 4864

It is possible to keep in memory the information if last character was a space or not..

#include <iostream>
#include <string>
#include <cctype>

std::string initials(const std::string &w) {
    char space = ' ';
    std::string a;
    int mode = 0;
    for (int i = 0; i < w.size(); ++i) {
        if (w[i] == space) {
            mode = 0;
        } else {
            if (mode == 0) a.push_back(w[i]);
            mode = 1;
        }
    }
    return a;
}

int main()
{
    std::cout<<  initials(std::string(" Julian     Rodriguez        Antonio "))<<std::endl;
}

EDIT: thanks to a suggestion of Pete Becker, here is a clearer implementation.

std::string initials(const std::string &w) {
    char space = ' ';
    std::string a;
    bool skipping_spaces = true;
    for (int i = 0; i < w.size(); ++i) {
        if (w[i] == space) {
            skipping_spaces = true;
        } else {
            if (skipping_spaces) a.push_back(w[i]);
            skipping_spaces = false;
        }
    }
    return a;
}

Upvotes: 2

Related Questions