Informatica Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
public class ReplaceString {
public static void main(String[] args) {
replace("anonymous", "abcs");
}
private static String replace(String input1, String input2) {
char[] arr1 = input1.toCharArray();
char[] arr2 = input2.toCharArray();
char[] temp = new char[input2.length()];
int i = 0;
for (int j = 0; j < arr2.length; j++) {
if (i < arr1.length) {
if (arr1[i] == arr2[j]) {
temp[j]=arr2[j];
i++;
continue;
} else {
temp[j]=arr2[j];
i++;
}
}else{
temp[j]=arr2[j];
}
}
return temp.toString();
}
}
More efficend code
public class ReplaceString {
public static void main(String[] args) {
System.out.println(replace("anonymous", "anonykggse"));
}
private static String replace(String input1, String input2) {
char[] arr1 = input1.toCharArray();
char[] arr2 = input2.toCharArray();
int i = 0;
StringBuilder sb = new StringBuilder();
for (int j = 0; j < arr2.length; j++) {
if (i < arr1.length) {
if (arr1[i] == arr2[j]) {
sb.append(arr2[j]);
i++;
continue;
} else {
sb.append(arr2[j]);
i++;
}
}else{
sb.append(arr2[j]);
}
}
return sb.toString();
}
}
//Code with less control statements
import java.util.*;
public class Informatica{
public static String stringReplace(String original, String change){
char[] input = original.toCharArray();
char[] out = change.toCharArray();
String output = "";
int j=0;
for(int i=0; i<change.length(); i++){
if(j < input.length && input[j] == out[i]){
output = output+""+input[i];
j++;
}else{
output = output + "" + out[i];
}
}
return output;
}
public static void main(String[] args){
System.out.println(Informatica.stringReplace("anonymous","anonymity"));
}
}
Replace a Substring in string using Java code follows like this:
String a = "Anonymousr How are you!";
String r = a.replace("mous","kggse");
print.i(r);
it will print: "Anonuykggse How are you!"
replace
public String replace(char oldChar,
char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
If the character oldChar does not occur in the character sequence represented by this String object, then a reference to this String object is returned. Otherwise, a new String object is created that represents a character sequence identical to the character sequence represented by this String object, except that every occurrence of oldChar is replaced by an occurrence of newChar.
Examples:
"mesquite in your cellar".replace('e', 'o')
returns "mosquito in your collar"
"the war of baronets".replace('r', 'y')
returns "the way of bayonets"
"sparring with a purple porpoise".replace('p', 't')
returns "starring with a turtle tortoise"
"JonL".replace('q', 'x') returns "JonL" (no change)
Parameters:
oldChar - the old character.
newChar - the new character.
Returns:
a string derived from this string by replacing every occurrence of oldChar with newChar.
- Jackmerius Tacktheritrix October 03, 2013