Epic Systems Interview Question
Software Engineer / Developersimport java.io.*;
import java.util.*;
class replace
{
public static void main(String [] args)
{
String totest[];
int i;
String test="She is a Hot girl";
String newString="";
StringTokenizer st= new StringTokenizer(test);
while(st.hasMoreTokens())
{
String temp=st.nextToken();
if( temp.compareTo("a")==0)
newString=newString+"the ";
else
newString= newString+ temp + " ";
}
System.out.println(newString);
}
}
Jim,
I am with you about the StringBuilder. Code is shorter with 'insert' instead of append because append adds to end of string. Also you can delete 'a' and insert 'the' because StringBuilder allows you to chain methods.
#include<iostream>
#include<cstdlib>
#include<cstring>
using namespace std;
int main(){
char str[]="a apple is a fruit and I like apple";
char *pch;
string newstr="";
/*init of newstr:two conditions*/
if(str[0]=='a'){
newstr="the";
}
cout<<str<<endl;
pch=strtok(str,"a");
newstr+=pch;
pch=strtok(NULL,"a");
while(pch!=NULL){
newstr+="the";
newstr+=pch;
pch=strtok(NULL,"a");
}
cout<<newstr<<endl;
return 0;
}
public class StrReplace {
public static String replace (String str, String toR, String r) {
String[] words= str.split(" ");
StringBuffer ret = new StringBuffer ( );
for (int i=0; i<words.length; i++) {
if ((words[i].toLowerCase()).equals(toR.toLowerCase())) {
if (i==0) { //make the first letter upper case
ret.append(r.substring(0, 1).toUpperCase());
ret.append(r.substring(1));
} else {
ret.append(r);
}
ret.append(" ");
} else {
ret.append(words[i]);
ret.append(" ");
}
}
return ret.toString();
}
public static void main(String [] args) {
String str = "A quick brown fox jumped over a bridge on a box.";
String toR = "a";
String r = "the";
System.out.println(StrReplace.replace(str, toR, r));
}
}
// program to replace a with the
//logic - iteration1 - count a in the string...
// - iteration 2 - start from end of the string,shifting the contents by
// number of 'a'* 2(becasue of t'he'),and keep on decreasing
// count value till we reach 0
#include<stdio.h>
#include<stdlib.h>
void main(){
char a[100];
int count = 0, i = 0, moves = 0;
printf("\n Enter a string ");
gets(a);
printf("\n string enterend is %s\n",a);
// counting number of 'a's in the string
while(a[i]!='\0'){
if(a[i] == 'a' && ((a[i+1] == ' ' && a[i-1] == ' ' && i!=0 )|| (i==0 && a[i+1] == ' ') || (a[i+1] == '\0' && a[i-1] == ' ' ) ) )
count++;
i++;
}
printf("\n length of the string : %d, and number of moves :%d",i,count);
while(count != 0 ){
//number of moves from back
moves = count * 2;
a[i+moves] = a[i];
if(a[i] == 'a' && ((a[i+1] == ' ' && a[i-1] == ' ' && i!=0 )|| (i==0 && a[i+1] == ' ')|| (a[i+1] == '\0' && a[i-1] == ' ' ) ) ){
a[i+moves] = 'e';
a[i+moves-1] = 'h';
a[i+moves-2] = 't';
count--;
}
i--;
printf("\n The string is %s\n",a);
}
// program to replace a with the
//logic - iteration1 - count a in the string...
// - iteration 2 - start from end of the string,shifting the contents by
// number of 'a'* 2(becasue of t'he'),and keep on decreasing
// count value till we reach 0
#include<stdio.h>
#include<stdlib.h>
void main(){
char a[100];
int count = 0, i = 0, moves = 0;
printf("\n Enter a string ");
gets(a);
printf("\n string enterend is %s\n",a);
// counting number of 'a's in the string
while(a[i]!='\0'){
if(a[i] == 'a' && ((a[i+1] == ' ' && a[i-1] == ' ' && i!=0 )|| (i==0 && a[i+1] == ' ') || (a[i+1] == '\0' && a[i-1] == ' ' ) ) )
count++;
i++;
}
printf("\n length of the string : %d, and number of moves :%d",i,count);
while(count != 0 ){
//number of moves from back
moves = count * 2;
a[i+moves] = a[i];
if(a[i] == 'a' && ((a[i+1] == ' ' && a[i-1] == ' ' && i!=0 )|| (i==0 && a[i+1] == ' ')|| (a[i+1] == '\0' && a[i-1] == ' ' ) ) ){
a[i+moves] = 'e';
a[i+moves-1] = 'h';
a[i+moves-2] = 't';
count--;
}
i--;
printf("\n The string is %s\n",a);
}
Awesome !!
You might want to keep the last print statement outside the while loop though !
public static void main(String args[])
{
String test="A quick brown fox jumped over a bridge on a box";
StringBuilder output=new StringBuilder();
StringTokenizer st=new StringTokenizer(test);
while(st.hasMoreTokens())
{
String temp=st.nextToken();
if(temp.compareTo("A")==0)
{
output.append(" The ");
}
else
if(temp.compareTo("a")==0)
{
output.append(" the ");
}
else
output.append(temp+" ");
}
System.out.println(output);
}
#include <iostream>
#include <string.h>
using namespace std;
int main() {
char input[] ="a person who is a boy is a man";
string new_string= "";
char deli [] = " ";
char *position;
position = strtok(input, deli);
while (1)
{
if (strcmp(position,"a")==0)
new_string += "the ";
else
{
new_string += position;
new_string += " ";
}
position = strtok(NULL, deli);
if (position==NULL)
break;
}
cout<<new_string;
}
Python working code.
"""
@Python 2.7
Given a string...replace all occurances of a with the.
eg. A quick brown fox jumped over a bridge on a box.
should change to
The quick brown fox jumped over the bridge on the box.
You cannot use the inbuilt replace function for string manipulation.
- Troy on October 07, 2010 Report Duplicate | Flag
"""
class AtoThe(object):
def __init__(self, inputs):
if inputs is None:
print 'invalid inputs'
self._input = inputs
def fromAToThe(self):
input = self._input.split()
output = []
for c in input:
if c == 'a':
output.append('the')
elif c == 'A':
output.append('The')
else:
output.append(c)
return ' '.join(output)
if __name__ == '__main__':
a = AtoThe('A quick brown fox jumped over a bridge on a box.')
print a.fromAToThe()
Here is a working code in C++. I have assumed that we need not replace the occurrence of 'a' when it is a part of another word. We only replace it when 'a' itself is a word.
#include<cstdio>
#include<iostream>
#include <string.h>
using namespace std;
int main()
{
char str[100];
int i;
scanf("%[^\n]s", str);
for (i=0; i<strlen(str); i++)
{
if (i==0 && (str[i]=='a' || str[i]=='A') && str[i+1]==' ')
{
cout<<"The";
}
else if((str[i]=='a' || str[i]=='A') && str[i+1]==' ' && str[i-1]==' ')
{
cout<<"The";
}
else if (i==(strlen(str)-1) && (str[i]=='a' || str[i]=='A') && str[i-1]==' ')
{
cout<<"The";
}
else
{
cout<<str[i];
}
}
return 0;
}
import java.util.*;
public class ReplaceA{
public static void main(String args[]){
String str = "A quick brown fox jumped over a bridge on a box";
StringTokenizer token = new StringTokenizer(str," ");
String newString = "";
while(token.hasMoreTokens()){
String tempString = token.nextToken();
if(tempString.equalsIgnoreCase("A")){
tempString = "The";
}
newString = newString + " " + tempString;
}
System.out.println(newString);
}
}
Much simpler..
public class epic28 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "A quick brown fox jumped over a bridge on a box";
String[] st = str.split(" ");
for(int i = 0;i < st.length;i++)
if(st[i].equalsIgnoreCase("a"))
st[i] = "the";
for(int i = 0;i < st.length-1;i++)
System.out.print(st[i]+" ");
System.out.print(st[st.length-1]+" ");
}
}
#include<string.h>
#include<vector.h>
#include<iostream>
#include<stdlib.h>
int main() {
std::string NewStr;
std::string OrigStr=std::string("A boy is playing in a garden.");
std::size_t LengthStr = OrigStr.length();
OrigStr = ' '+OrigStr;
OrigStr = OrigStr+' ';
for (int i=1; i<LengthStr+1; i++) {
if(OrigStr[i-1]==' '&&OrigStr[i+1]==' ') {
if (OrigStr[i]=='a') {
NewStr.push_back('o');
NewStr.push_back('n');
NewStr.push_back('e');
} else if(OrigStr[i]=='A') {
NewStr.push_back('O');
NewStr.push_back('N');
NewStr.push_back('E');
} else NewStr.push_back(OrigStr[i]);
} else NewStr.push_back(OrigStr[i]);
}
return 0;
}
this code converts the a's which are a part of a word, too. Therefore, it is not quite correct. you should seek for the individual a's which are words itself.
riza,
The question says "ALL occurances of a with the"; Therefore a solution that ignores whether 'a' is part of the word or not is still VERY correct unless of course you have already done the exam and seen the question structured differently. That said replace "a " (with space next to it) instead of "a" should take care of your concerns. And my java solution would be a StringBuilder object with a single for loop
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "I am a boy.";
string temp;
cout<<s<<endl;
for (int i=0; i<s.length(); ++i)
{
if (s[i]=='a')
{
temp.push_back('o');
temp.push_back('n');
temp.push_back('e');
}
else
{
temp.push_back(s[i]);
}
}
cout<<temp<<endl;
system("pause");
return 0;
}
Sorry!!
- sanzoy October 08, 2010The above is for another post, replacing 'a' with 'one' and 'A' with 'ONE'.
However, for this post, the clue is the same.
btw: I don't quite understand how vijay's code could solve the problem.
Maybe vijay could explain more.