Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
private static int numOfWords(String str) {
char[ ] arr = str.toCharArray();
int count = 0;
if(arr[0] != ' ') {
count++;
}
for(int i=1; i<arr.length; i++) {
if(arr[i-1]==' ' && arr[i]!=' ') {
count++;
}
}
return count;
}
# include<stdio.h>
# include<conio.h>
# include<stdlib.h>
int find(char *s)
{
int flag=0,count=0;//when flag is made 1 then it means that there are characters in between two white spaces
while(*s!='\0')
{
if(*s==' ')
{
if(flag==1)
{
count++;
flag=0;
}
}//end when white spaces occur
else if(flag==0)//character other than alphabets
flag =1;
s++;
}//end of while loop
if(flag==1)
count++;//for the last word
return count;
}//end of function
int main()
{
char s[100];
int count;
printf("enter the string");
gets(s);
count=find(s);
printf("The number of words present in the string are %d",count);
getch();
return 0;
}//end of main function
one line code in C#
private static int CountWords(string s)
{
return s.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries).Count();
}
#include<stdio.h>
#include<string.h>
#include <conio.h>
int main()
{
char ch[1000];
printf("Please Enter the String\n");
gets(ch);
int i=0,k=0,j;
int len=strlen(ch);
while(ch[i]!='\0')
{
if(ch[i]==' '||ch[i]=='\t') {i++;}
else{
while((ch[i++]!=' '&& i<len)&&(ch[i++]!='\t' && i<len));
k++;
}
}
printf("The number of words is=%d", k);
getch();
}
public class WordCount {
public static void main(String[] args) {
String s = " the quick brown fox jumped over the fence ";
boolean flag = false;
int wc = 0;
for (Character c : s.toCharArray()) {
if (c == ' ')
flag = false;
else if (flag == false && c != ' ') {
wc++;
flag = true;
}
}
System.out.println(" " + wc);
}
}
- Anonymous October 03, 2012