问题
I am doing homework related to Java language. I am reading a text file from a website via socket with:
BufferedReader br = new BufferedReader(inr);
while((line2 = br.readLine()) != null)
{...}
I need to replace the nth occurrence of the target word with a replacement word only if n is odd. For example:
line2 is readed as "ces11111111". target word is 11 ; replacement word is CS219. Thus , result line is cesCS21911CS21911.
How can I achieve this ? Please help me to complete my homework.
回答1:
Here is my code:
public static String replaceIfOdd(String stringToChange,
String searchingWord, String replacingWord) {
final String separator = "#######";
String splittingString = stringToChange.replaceAll(searchingWord,
separator + searchingWord);
String[] splitArray = splittingString.split(separator);
String result = "";
for (int i = 0; i < splitArray.length; i++) {
if (i % 2 == 1)
splitArray[i] = splitArray[i].replace(searchingWord,
replacingWord);
result += splitArray[i];
}
System.out.println(result);
return result;
}
Way to call it:
replaceIfOdd("ces11111111", "11", "CS219");
The logic behind this is the following:
I replace all the occurrences of the searchingWord
with separator + searchingWord
.
After that I just split the resulting string using the split
function.
Then I loop through all the elements of the array and I make the right replacement only when the searchingWord
appears in an odd position into the array and, at the same time, I just recreate the string with the right replacements done.
Hope this is what you were searching for!
P.S.: I used a string separator
in order to break down the stringToChange
, obviously if into your stringToChange
there was such a string, the method wouldn't give you the right result ... I will try to think about a different implementation if you are worried about it. Ciao!
回答2:
String in = "ces11ccc11ceb11";
in = "ces11111111";
String target = "11";
String replacement = "CS219";
int j=0;
boolean flag=true;
String result = "";
for(int i=0;i<in.length();i++)
{
if(in.length()-i<target.length()) break;
if(in.charAt(i)==target.charAt(0))
{
if(in.substring(i, i+target.length()).equals(target))
{
if(flag)
{
result += replacement;
}
else result += target;
flag=!flag;
i = i+target.length()-1;
}
else result += in.charAt(i);
}
else
{
result += in.charAt(i);
}
}
System.out.println(result);
来源:https://stackoverflow.com/questions/19856042/replacing-nth-occurrence-of-word-with-a-replacement-word-in-java