In this series of articles, we are going to solve some different algorithms and problems, mainly through C++. The goal of the whole series is to learn together how to solve complex problems and improve our logic skills. We are going to publish our own solution to the problem. Then you can send us an e-mail or contact us on social networks to propose your own personal solution to the same problem or to let us know how we can optimize our script. If your algorithm is correct we will update the article with your solution. We will also credit you for your help.

The problem of today:

Divide a string in single words. Count how many letters has every word. Count how many words and how many letters there are in total.

OUR SOLUTION (C++)

#include <iostream>
#include <vector>

using namespace std;

void lengthOfAllTheWords(string s, vector* words, vector* solution) {
    // Count the length of every single word
    int count = 0;

    // Memorize the word
    string word = "";

    // For every character in the string
    for (size_t l = 0; l < s.length(); ++l) {
        // Get one single char
        char c = s[l];

        // If is a blank space and count is not zero
        // Save the word and its length and reset the variables
        if (c == ' ' && count != 0) {
            // Save
            solution->push_back(count);
            words->push_back(word);

            // Reset
            count = 0;
            word = "";
        }

        // Else
        else {
            // Add char to the word
            word += c;

            // Count one more letter
            ++count;

            // If is the last char and count is not zero
            // Save the word and its length
            if (l == s.length() - 1 && count != 0) {
                solution->push_back(count);
                words->push_back(word);
            }
        }

    }
}


int main() {
    string val = "We are C.M.Programmers";
    vector solution;
    vector words;
    lengthOfAllTheWords(val, &words, &solution);

    int countLetters = 0;
    for (size_t a = 0; a < solution.size(); ++a) {
        cout << solution[a] << " -> " << words[a] << endl;
        countLetters += solution[a];
    }

    cout << "Total words: " << solution.size() << endl;
    cout << "Total letters: " << countLetters << endl;

    return 0;
}

HOW IT WORKS

Our idea is to cycling through every character of the string with a for loop.

// For every character in the string
for (size_t l = 0; l < s.length(); ++l) {

If the c char is a blank space and you already counted one or more letter then save the word and its letters amount.

// If is a blank space and count is not zero
// Save the word and its length and reset the variables
if (c == ' ' && count != 0) {
  // Save
  solution->push_back(count);
  words->push_back(word);

  // Reset
  count = 0;
  word = "";
}

If not, add this char to the string that will compose the word and count one more letter.

// Add char to the word
word += c;

// Count one more letter
++count;

If you reach the last step of the loop and there is a word to save (count != 0) then save it.

// If is the last char and count is not zero
// Save the word and its length
if (l == s.length() - 1 && count != 0) {
  solution->push_back(count);
  words->push_back(word);
}


We saved all the words and their amount of letters in two different vectors. We cycle to these vectors and print all the words and their letters count. The total words amount is the size of the vectors. The total amount of letters is the sum of the letters of all the words.

int countLetters = 0;
for (size_t a = 0; a < solution.size(); ++a) {
  cout << solution[a] << " -> " << words[a] << endl;
  countLetters += solution[a];
}

cout << "Total words: " << solution.size() << endl;
cout << "Total letters: " << countLetters << endl;




Solution by Michael Aaron Murphy on Google+

Here's a simpler, more efficient Rust solution that doesn't require heap allocations (no vectors needed).
https://play.rust-lang.org/?gist=c95b535c0f8af329d6df4dcedf8df87c&version=stable

Also, your solution isn't counting letters. It's counting bytes. Ideally, you'd want to count graphemes, but counting characters (not the same as bytes) works in most scenarios.

use std::io::{self, Write};

fn main() {
    let stdout = io::stdout();
    let mut stdout = stdout.lock();
    
    let input = "We are C.M.Programmers and in this page you can find all the informations";
    let (mut words, mut characters) = (0, 0);
    
    for word in input.split_whitespace() {
        let nchars = word.chars().count();
        characters += nchars;
        words += 1;
        let _ = writeln!(stdout, "{} -> {}", nchars, word);
    }
    
    let _ = writeln!(stdout, "Total Words: {}\nTotal Characters: {}", words, characters);
}

NEWSLETTER

Do not lose our new articles! Sign up to our newsletter to receive one and only one email every time a new article is online. You will be able to unsubscribe to the service later if you want. What are you waiting for?

Sandro Maglione
Designer / Developer

I really love to share all the secrets and the tricks, which I learned surfing on the web or studing on my own, with some articles or tutorial online. I believe that through coding you can create a real piece of art by using only your imagination and your skills.