Thursday, February 23, 2012

Complete the function getFirstLetterWord,

Complete the function getFirstLetterWord, which takes in a string text,consisting of only lowercase letters and spaces. A word is a maximal sequence of consecutive letters. There may be multiple spaces between words. Also, text may contain only spaces.
The function getFirstLetterWord is expected to return the word which is formed by concatenating the first letter from each word in text, in the order they appear.Return an empty string is no word is possible

Sample Test Cases:

Input #00:
the quick brown fox jumped over the lazy dog

Output #00:
tqbfjotld

Explanation:
Picking up the 1st character from each of the words in the sentence, we get, tqbfjotld


Input #01:
dice     gambling     las vegas

Output #01:
dglv

Explanation:
Ignore multiple spaces, picking the 1st character from dice, gambling, las and vegas results in dglv




import java.io.FileReader;
 
class WordCount 
{
 
public static void main(String args[]) throws Exception 
{
 
String text="dice       gambling       las    vegas";//"the quick brown fox jumped over the lazy dog";
 
char ch[]=new char[text.length()];
char c;
boolean lastWhite = true;
String whiteSpace = " \t";
int i=0;
 
   for(i=0;i<text.length();i++)
   {
        c=text.charAt(i);
 
        int index = whiteSpace.indexOf(c);
        if (index == -1)
        {
                  if (lastWhite == true)
                  {
                      ch[i]=c;
                  }
        
          lastWhite = false;
 
        }
 
        else
 
        {
 
                lastWhite = true;
 
        }
 
  }
 
    String ss = new String(ch);
    System.out.println(ss);
 
 }
 
}
Run Here http://ideone.com/zVquq 

1 comment :

Atul anand said...

code in C :-



void printFirstChar(char str[])
{
int i,len;

len=strlen(str);
for(i=0;i<len;)
{

if(str[i]==' ' || str[i]=='\t')
{
i++;
continue;

}
printf("%c",str[i]);

while(str[i]!=' ')
{
i++;
if(i==len)
break;
}
}

}