Amazon Interview Question
Software Engineer in TestsAssuming " " to be replaced....
String a = "There are multiple spaces";
while (a.contains(" ")){
a=a.replace(" ", " ");
}
System.out.println(a);
}
This is a version of a possible solution:
string str = "Test String to be displayed";
char *ptr = (char *)str.c_str();
int index = 0,w_start = 0,w_end = 0;
while(*ptr) {
w_end = w_start;
while(*ptr && *ptr != ' '){
ptr++;
w_end++;
}
while(w_start < w_end)
str[index++] = str[w_start++];
str[index++] = ' ';
while(*ptr && *ptr == ' '){
w_start++;
ptr++;
}
}
for(; index < str.size(); index++)
str[index] = '\0';
cout << "Final: " << str << endl;
This code is very simple.
Just compare every element with every other element. If they both are spaces( in my prog i did for dashes!) they replace with a single dash and decrement the count of i by one.
Hope it helps!
private static void MultipleSpaces(){
String str = "Test-String-----to-be--displayed--";
for(int i=0;i<str.length()-1;i++){
if(str.charAt(i)=='-' && str.charAt(i+1)=='-'){
i--;
str=str.replace("--","-");
}
}
System.out.println(str);
}
#include<stdio.h>
#include<string.h>
int main()
{
char str[50];
int len,i=0,j,spaces=0;
clrscr();
printf("\n Enter the String\n");
gets(str);
len=strlen(str);
printf("\n Length of the String is %d\n",len);
for(j=0;j<=len;j++)
{
if(str[j]==' ')
spaces++;
else
{
if(spaces>0)
{
str[i]=' ';
i++;
}
str[i]=str[j];
i++;
spaces=0;
}
}
str[i]='\0';
printf("Result String %s",str);
}
void replace(char *str)
{
int i = 1; j = 1; //notei and j = 1, not 0
char *cur = str;
while(cur[i])
{
if(cur[i] == ' ')
{
if(cur[i-1] == ' ') //first occurence
{
//ignore it
}
}
else
{
cur[j++] = cur[i];
}
}
#define TrimCharacter '-'
char * Trim(char * inputString,int l)
{
char *p,*q;
q = p = inputString;
while(*p){
if((*p != TrimCharacter) || (*q != TrimCharacter)) {
*q = *p;
q++;
}
p++;
}
*q = 0;
return inputString;
}
<pre lang="c++" line="1" title="CodeMonkey19636" class="run-this">#include<iostream>
#include<string>
using namespace std;
int main()
{
string s=" Hello, how r u???????";
int pos,i=0;
for(i=0;i<s.length();i++)
{
if(s[i]==' ')
{ if(i!=0)
i=i+1;
while(s[i]==' ')
{
s.erase(s.begin()+i);
}
}
}
cout<<s<<"\n";
return 0;
}</pre><pre title="CodeMonkey19636" input="yes">
</pre>
public class nr_LimitSpaceBetweenWordsInAStringToOne
{
/**
* @param args
*/
public static void main(String[] args)
{
String s = "Test String to be displayed ";
//String s = "AA B C D";
int count = 0;
for(int i=0;i<s.length();i++)
{
count = 0;
while(i<s.length() && s.charAt(i)==' ')
{
i++;
count++;
}
if(count > 1)
{
System.out.println("i= "+i+" count= "+count);
s=s.substring(0,i-count+1)+s.substring(i,s.length());
System.out.println(s);
i = 0;
}
}
System.out.println("");
System.out.println("Final String after removing all extra spaces is: ");
System.out.println(s);
}
}
- gevorgk March 09, 2010