Amazon Interview Question
Software Engineer / DevelopersAny reason of declaring tmp_str inside the loop as i guess it will create a new tmp_str variable in each loop iteration?
Maintain a set of TAB SPACE EOF \O and \n
for every character you read from the file check if it belongs to this set. If it does then check if the previous element belongs to this set as well, if not then increment the count else do nothing
eg: I am a Student.
No. of words = 4 {space(1) space(4) space(6) EOF(15)} Where the number in the bracket represents the position in the string
I am a Student.
No. of words = 4 {Space(1) Space(4) Space(5) Space(7) EOF(16)} The space at the 5th position is discarded as it is a successor of another character from the set mentioned above so we don't count then
Formatted version
Maintain a set of TAB SPACE EOF \O and \n
for every character you read from the file check if it belongs to this set. If it does then check if the previous element belongs to this set as well, if not then increment the count else do nothing
eg:
I am a Student.
No. of words = 4 {space(1) space(4) space(6) EOF(15)} Where the number in the bracket represents the position in the string
I am a Student.
No. of words = 4 {Space(1) Space(4) Space(5) Space(7) EOF(16)} The space at the 5th position is discarded as it is a successor of another character from the set mentioned above so we don't count then
<pre lang="c++" line="1" title="CodeMonkey79468" class="run-this">It depends on what does one mean by "word" here? If characters between spaces and TABs and EOL, then code maybe like this:
- Anonymous November 02, 2010int main()
{
ifstream in_file("c:\\test.txt");
int words_cnt(0);
while(in_file.good())
{
string tmp_str;
in_file >> tmp_str;
++words_cnt;
}
cout << "Words in file: " << words_cnt << "\n";
return 0;
}
</pre><pre title="CodeMonkey79468" input="yes">
</pre>