Given a string, if string has " is "(before and after space) in it: replace it with "is not".
Example:
- Original: This is a string
- New: This is not a string
I am implementing it using string/char arrays. Is there any better way to solve this question? I have a feeling that it can be solved with a regular expression. Can anyone suggest some better/different approach to solving this question?
/**
*
*
* Given a string. If string has " is "(before and after space) in it: replace it with "is not"
* e.g.,
* Original : This is a string
* New : This is not a string
*/
public class ReplaceString {
public static void main(String[] args) {
String s = "This is bag";
replaceIs(s);
}
public static void replaceIs(String s) {
/* Find number of "is" in string to get length of new array*/
String wordToFind = " is ";
Pattern word = Pattern.compile(wordToFind);
Matcher match = word.matcher(s);
int counterOfWord = 0;
while (match.find()) {
++counterOfWord;
}
int lengthOfNewArray = s.length() + (counterOfWord * 4);
char[] originalCharArray = s.toCharArray();
char[] newCharArray = new char[lengthOfNewArray];
/* Parse String from the end and if " is " encounters, replace it with " is not" */
int indexInNewArray = lengthOfNewArray;
int i = originalCharArray.length - 1;
while ( i >= 0 ) {
if (originalCharArray[i] == ' ' && originalCharArray[i - 1] == 's' && originalCharArray[i - 2] == 'i' && originalCharArray[i - 3] == ' ' ) {
newCharArray[indexInNewArray - 1] = ' ';
newCharArray[indexInNewArray - 2] = 't';
newCharArray[indexInNewArray - 3] = 'o';
newCharArray[indexInNewArray - 4] = 'n';
newCharArray[indexInNewArray - 5] = ' ';
newCharArray[indexInNewArray - 6] = 's';
newCharArray[indexInNewArray - 7] = 'i';
newCharArray[indexInNewArray - 8] = ' ';
i = i - 4;
indexInNewArray = indexInNewArray - 8;
} else {
newCharArray[indexInNewArray - 1] = originalCharArray[i];
--indexInNewArray;
--i;
}
}
System.out.println(String.valueOf(newCharArray));
}
}
1 Answer 1
I suggest:
String replaceIs(String s) {
return s.replace(" is ", " is not ");
}
In Oracle Java 8, this uses a regular expression internally, but in Java 9 it will be implemented with a more efficient algorithm.
By the way, will your code throw an ArrayIndexOutOfBoundsException
when your string starts with a space?
String::replaceAll()
? \$\endgroup\$Regex
to make it more interesting \$\endgroup\$Regex
, just usingchar[]
logic. The easiest wat to construct the newString
is by usingStringBuilder.append()
\$\endgroup\$