How do i split a string word by word and store each word into a hashtable? please help


Thanks,

Saula

Think about it first. If you have a string like so :
string sentence = "This is a sentence that needs to be splitted";
how would you go ahead and get word by word? How would you start? Use this as an exercise.

Map is a kind of hashtable isnt it? Anyway
I wanted to try so I came up with this:

#include "stdafx.h"
#include <map>
#include <string>
#include <iostream>
#include <fstream>

int main()
{
	using namespace std;
	map<string, int> m;
	string s = "Hello my name is Andreas.";
	for(string::const_iterator first = s.begin(), last = s.begin(); last != s.end(); last++) {
		if(*last == ' ' || last == s.end()-1) {
			if(*first == ' ') first++;
			string a(first, last);
			++m[a];
			first = last;
		}
	}

	for(map<string, int>::const_iterator it = m.begin(); it != m.end(); it++)
		cout << it->first << "\t" << it->second << endl;

	cin.get();
	return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.