15S-Section-Solution

15S-Section-Solution - CS106X Handout 15S Autumn 2010...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: CS106X Handout 15S Autumn 2010 October 6 th 8 th , 2010 Section Solution Solution 1: URL Parameter Map Map<string> extractQueryMap(string url) { Map<string> parameters; int index = url.find('?'); if (index == string::npos) return parameters; string query = url.substr(index + 1); index = query.find('#'); if (index != string::npos) { query = query.substr(0, index); // chop off hash } Vector<string> pairs = Explode(query, '&'); for (int i = 0; i < pairs.size(); i++) { Vector<string> components = Explode(pairs[i], '='); string key = components[0]; string value = "true"; if (components.size() > 1 && !components[1].empty()) { value = components[1]; } parameters[key] = value; } return parameters; } Solution 2: Publishing Stories Theres the one-pass approach that just appends characters from the template to the running story, unless that character is '{' , in which case we extract everything up through the matching '}' and substitute it with a string from the data map. string SubstituteTokens(string storyTemplate, Map<string>& data) { string story; for (int i = 0; i < storyTemplate.size(); i++) { if (storyTemplate[i] != '{') { story += storyTemplate[i]; } else { int j = storyTemplate.find('}', i + 1); string token = storyTemplate.substr(i + 1, j - i - 1); story += data.get(token); i = j; } } return story; } 2 Another approach is to iterate over the data map and drive the substitution that way. Its less efficient, but its another way to think about the problem and is a perfectly acceptable answer for the purposes of a discussion section. string SubstituteOneToken(string story, string token, string value) { int start = 0; while (true) { int found = story.find(token); if (found == string::npos) return story; story.replace(found, token.size(), value); start = found + value.size() + 1; } } string SubstituteTokens(string storyTemplate, Map<string>& data) { string story = storyTemplate; foreach (string token in data) { story = SubstituteOneToken(story, '{' + token + '}', data.get(token)); } return story; } Solution 3: Chain Reactions As with all nontrivial problems, there are several reasonable approaches. As with all nontrivial problems, there are several reasonable approaches....
View Full Document

Page1 / 6

15S-Section-Solution - CS106X Handout 15S Autumn 2010...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online