Issue
Trying to replace every second occurence of "Object-oriented programming" substring in a given string "text". I am a beginner in Java and the aim of the task is to use only String class methods. Below is what I came up with so far. Thanks in advance for any help)
public class ExerciseString {
public static void main(String[] args) {
String s = "Object-oriented programming is a programming language model organized around objects rather than \"actions\" and data rather than logic. Object-oriented programming blabla. Object-oriented programming bla.";
changeToOOP(s);
}
static void changeToOOP (String text) {
String str = "Object-oriented programming"; // добавить игнорирование регистра
String str2 = "OOP";
int index = 0;
int count = 0;
while (true) {
index = text.indexOf(str, index);
if (index != -1) {
count++;
index += str.length();
if (count % 2 == 0){
text = text.replace(text.substring(index - str.length(), index), str2);
}
} else {
break;
}
}
System.out.println(text);
}
}
Solution
String::replace
replaces every occurrence and therefore its use for your requirement is not right. You can use
text = text.substring(0, index) + str2 + text.substring(index + str.length());
Note that 0 % 2==0
; therefore, if you want to replace the occurrence number second, fourth, sixth and so on, use count % 2 != 0
in the inner if
block. Also, increment index
and count
after processing the previous index
and count
values i.e. move the following after the inner if
block:
count++;
index += str.length();
Demo:
public class ExerciseString {
public static void main(String[] args) {
String s = "Object-oriented programming is a programming language model organized around objects rather than \"actions\" and data rather than logic. Object-oriented programming blabla. Object-oriented programming bla.";
changeToOOP(s);
}
static void changeToOOP(String text) {
String str = "Object-oriented programming"; // добавить игнорирование регистра
String str2 = "OOP";
int index = 0;
int count = 0;
while (true) {
index = text.indexOf(str, index);
if (index != -1) {
if (count % 2 != 0) {
text = text.substring(0, index) + str2 + text.substring(index + str.length());
}
count++;
index += str.length();
} else {
break;
}
}
System.out.println(text);
}
}
Output:
Object-oriented programming is a programming language model organized around objects rather than "actions" and data rather than logic. OOP blabla. Object-oriented programming bla.
Answered By - Arvind Kumar Avinash
Answer Checked By - Senaida (JavaFixing Volunteer)