Reputation: 25
If we have
String x="Hello.World";
I'm looking to replace that '.'
with "Hello"
, as to have: "HelloHelloWorld"
.
The problem is, if I have:
String Y="Hello.beautiful.world.how.are.you;"
the answer would have to be "HelloHellobeautifulbeautifulworldworldhowhowareareyouyou"
Keep in mind that I can't use arrays.
Upvotes: 1
Views: 196
Reputation: 25
This is what i have:
public String meowDot(String meow){
int length = meow.length();
String beforeDot = "";
String afterDot;
char character;
for(int i=0; i < length; i++){
character = meow.charAt(i);
if (i < largo - 1 && character == '.'){
beforeDot += meow.substring(0, i) + meow.substring(0, i);
afterDot = meow.substring(i, length);
meow = afterDot;
} else if(i == length - 1 && character != '.'){
afterDot += meow + meow;
}
}
return beforeDot;
}
Upvotes: -2
Reputation: 2037
Think of the problem like a pointer problem. You need to keep a running pointer
pointed at the last place you looked (firstIndex
in my code), and a pointer at your current place (nextIndex
in my code). Call subString()
on whatever is between those places (add 1 to firstIndex
after the first occurrence because we don't need to capture the "."), append it twice to a new string, and then change your pointers. There is probably a more elegant solution but, this gets the job done:
String Y="Hello.beautiful.world.how.are.you";
int firstIndex=0;
int nextIndex=Y.indexOf(".",firstIndex);
String newString = "";
while(nextIndex != -1){
newString += Y.substring(firstIndex==0 ? firstIndex : firstIndex+1, nextIndex);
newString += Y.substring(firstIndex==0 ? firstIndex : firstIndex+1, nextIndex);
firstIndex=nextIndex;
nextIndex=Y.indexOf(".", nextIndex+1);
}
System.out.println(newString);
Output:
HelloHellobeautifulbeautifulworldworldhowhowareare
Upvotes: 1
Reputation: 1029
I think you can just use regex replacements to achieve that. In a regex, you can use so called "capture groups". You match a word plus a dot with your regex and then you replace it with two times the matched word.
// Match any number of word characters plus a dot
Pattern regex = Pattern.compile("(\\w*)\\.");
Matcher regexMatcher = regex.matcher(text);
// $1 is the matched word, so $1$1 is just two times that word.
resultText = regexMatcher.replaceAll("$1$1");
Note that I didn't try it out since it would probably take me half an hour to set up the Java environment etc. But I am pretty confident that it works.
Upvotes: 3