Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
//c code for this
#include<stdio.h>
#include<string.h>
main()
{
char* st="the dark night";
char str1[40]="";
char temp[4];
int i,len=strlen(st),count=0;
for(i=0;i<len;i++)
{
if(st[i]==' ')
{
itoa(count,temp,10);
strcat(str1,temp);
count=0;
}
else
{
count++;
}
}
itoa(count,temp,10);
strcat(str1,temp);
printf("%s",str1);
return 0;
}
# Ruby code
str = "career cup."
str_length = str.length
result = {}
start_chr_pos = curr_chr_pos = 0
while curr_chr_pos < str_length + 1 do
if str[curr_chr_pos] === " " || curr_chr_pos == str_length
result[str[start_chr_pos..curr_chr_pos-1]] = curr_chr_pos - start_chr_pos
start_chr_pos = curr_chr_pos + 1
end
curr_chr_pos += 1
end
puts result
>> {"career"=>6, "cup."=>4}
# ========== Very short form
# puts str.split(" ").inject(Hash.new { |h,k| h[k] = []}) { |h,s| h[s] << s.length; h}
http://jsfiddle.net/abhimehta/THj8r/
var s = "career cup.";
var count = 1;
for(i=0; i<s.length; i++)
{
if(s[i] == " ")
{
document.write((count-1)+"<br/>");
count = 0;
}
else if( i == s.length-1 )
document.write(count);
count++;
}
just to modify a bit on your code, since we need to return a string, may be this works:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to convert the array into a String.</p>
<button onclick="myFunction()">Try it</button>
<script type="text/javascript">
function myFunction()
{
//var s = "career cup.";
var s= "Dark, Knight, Rises!";
var ans=[];
var count = 1;
for(i=0; i<s.length; i++)
{
if(s[i] == " ")
{
// document.write((count-1)+"<br/>");
ans.push(count-1);
count = 0;
}
else if( i == s.length-1 )
{ ans.push(count);
}
// document.write(count);
count++;
}
ans.toString();
//document.write(ans);
var x=document.getElementById("demo");
x.innerHTML=ans;
}
</script>
</body>
</html>
- ethioer July 21, 2012