Facebook Interview Question for Software Engineer / Developers






Comment hidden because of low score. Click to expand.
3
of 3 vote

public class CountWords {

	public static void main(String[] args) {
		String str = "  an b  c   d";
		//String str = " c        d";
		System.out.println("String: " + str);
		System.out.println("Word Count: " + countWords(str));
	}
	
	public static int countWords(String string) {
		if (null == string) { return -1; }
		
		int count = 0;
		int len = string.length();
			
		char lastChar = string.charAt(0);
		for (int i=0; i<len; i++) {
			if (string.charAt(i) == ' ' && lastChar != ' ') {
				++count;
				lastChar = ' ';
			}
			lastChar = string.charAt(i);
		}
		if (lastChar != ' ') {
			++count;
		}
		return count;
	}
}

- bawet December 25, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

If you are using java, you can use stringtokenizer class. with dilimiter as " " (single space).

- Psycho July 12, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Psycho, you are right but I believe they wanted to see whether you can come up with an algorithm and not how well you know an API (here Java SE).

- Safi December 17, 2014 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

If previous one is a 'space' and current character is not a space then increase the word count.

#include <stdio.h>

int countWords (char *str) {
  int index = 0 ;
  char lchar = ' ', cur ;
  int count = 0 ;

  if ( str == NULL )
    return 0 ;
  while (str[index] != '\0') {
    if (str[index] != ' ' && lchar == ' ')
      count ++ ;
    lchar = str[index++] ;
  }
  return count ;
}

int main () {
  char *str = "a " ;
  printf ( "\nCount words = %d\n", countWords (str) ) ;
  return 0 ;
}

- Psycho October 23, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class CountWordInSentence {

public static void main(String args[])
{
String sentence="Hello World is beautiful ";
int count= countWords(sentence);
count=count+1;
System.out.println("Total words: "+count);
}

private static int countWords(String sentence) {
int wordCount=0;
for(int i=0;i<sentence.length();i++)
{
if(i==sentence.length()-1 &&(sentence.charAt(i)==' ' ))
{
System.out.println("found space at: "+i);
break;
//wordCount++;
}
else if(sentence.charAt(i)==' ' && sentence.charAt(i+1)!=' ')
{
System.out.println("found space at: "+i);
wordCount++;
}
}
return wordCount;
}

}

- Miss N April 16, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class CountWordInSentence {

public static void main(String args[]){
String sentence1=" Hello World is beautiful ";
String sentence="Hello ";
System.out.println(sentence+"\nTotal words: "+countWords(sentence));
}

private static int countWords(String sentence) {
int wordCount=0;
if (sentence == null) return wordCount;
for(int i=1;i<sentence.length();i++){
if(sentence.charAt(i-1) == ' ' && sentence.charAt(i) != ' ')
wordCount++;
}
if(sentence.charAt(0)!= ' ') wordCount++;
return wordCount;
}

}

- Anonymous May 01, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

Wrong~

- zhangfan555 November 08, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

class countwords{
string m_str;
void trim()
{
size_t len = m_str.length();
if(len != 0)
{
size_t count= 0;
size_t b = m_str.find_first_of(" "), e = m_str.find_last_of(" ");
while( (b= m_str.find_first_of(" ",b)) == 0)
m_str = m_str.substr(b+1,len);
len = m_str.length();
while( (e= m_str.find_last_of(" ",e)) == len-1){
m_str = m_str.substr(0,e);
len =m_str.length();

}

}
}
public :
countwords(string &str)
{
m_str = str;
}
countwords()
{

}
int count(){
trim();
size_t br =0;
int count =0;
while((br = m_str.find(" ",br))!= string::npos)
{
count++;
br++;
while(m_str[br] == ' ')
br++;

}
return count+1;
}
};

void main()
{
string str(" abcd efgh ijkl ");
countwords cn(str);
std::cout<<cn.count();
getchar();
}

- KP May 17, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <string>

using namespace std;

int count(string a)
{
int n = 0;
for(int i = 1; i <= a.length(); i++)
{
if(i == a.length() || a[i] == ' ') {
if(a[i - 1] != ' ') n++;
}
}
return n;
}

int main()
{
cout << count("a b cc ccccc") << endl;
cout << count("a") << endl;
cout << count("") << endl;
}

- Anonymous January 19, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int wordCount(String s){
return s.trim().split("\\s+").length;
}

- Anonymous February 16, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static int wordCount(String s) {

        int i = 0, wordCount = 0;
        boolean inSpace = true;
        while(i < s.length()) {
            char c = s.charAt(i);
            boolean isBlank = c == ' ';
            if(inSpace && isBlank) {
                // do nothing, still in space
            } else if(inSpace && !isBlank) {
                wordCount++; // got a new word! wohoo!
                inSpace = false;
            } else if(!inSpace && !isBlank) {
                // mid word, do nothing.
            } else if(!inSpace && isBlank){
                // oh snap, end of word! into space I go!
                inSpace = true;
            }
            i++;
        }
        return wordCount;
    }

- Jason Fotinatos February 22, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main (String args[]){
int i = count (" adfasdf asidfa asdfa sa as");
System.out.println(i);
}

public static int count (String s){
int count = 0;
boolean inWord = false;
boolean inSpace = true;
for (int i = 0 ; i< s.length (); i++){
if (s.charAt(i) == ' '){
if (inWord){
//count ++;
inWord = false;
}

inSpace = true;

} else {
if (inSpace){
count ++;
inSpace = false;
}
inWord = true;

}

}
return count;

}

- miaomiao July 03, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int CountWordsIn_A_Sentence(char * sentence)
{
    int c = 0;
    int p = 0;
    bool w = false;
    if(sentence == NULL)
        return -1;

    while(true)
    {
        if(sentence[p] == '\0')
            break;
        if(sentence[p] == ' ')
        {
            w = false;
        }
        else
        {
            if(!w)
                c++;
            w = true;
        }
        p++;
    }
    return c;
}

- Isaac Levy January 30, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int countWord(String str)
    {
	int cursor =0;
	int count =0;
	boolean word = false;
	
	while (cursor < str.length())
	{
	    char ch = str.charAt(cursor);
	    
	    if (ch==' ')
	    {
		if (word == true)
		{
		    count++;
		}
		word = false;
		cursor++;
	    }
	    else
	    {
		word = true;
		cursor++;
	    }
	}

	if (word== true)
	{
	    count++;
	}
	
	return count;
    }

- Anonymous June 23, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int WordCount(String str)
        {
            if(str == null) {return 0;}
            str = str.Trim();
            int wordCount = 0, index =0;
            while (index < str.Length)
            {
                // check if the current character is part of a word
                while (index < str.Length && !char.IsWhiteSpace(str[index]))
                {
                    index++;
                }
                
                wordCount++;
                
                // skip whitespace until next word
                while (index < str.Length && char.IsWhiteSpace(str[index]))
                {
                    index++;
                }
            }
            return wordCount;
        }

- Dillon May 23, 2017 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More