试图替换给定字符串“文本”中的“面向对象编程”子字符串的每一秒。我是Java的初学者,任务的目标是只使用String类方法。下面是我到目前为止想出的。预先谢谢你的帮助)
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);
}
}发布于 2022-10-03 18:07:26
String::replace替换了所有的事件,因此它在您的需求中的使用是不正确的。您可以使用
text = text.substring(0, index) + str2 + text.substring(index + str.length());请注意,0 % 2==0;因此,如果您想替换发生号第二、第四、第六等等,请在内部if块中使用count % 2 != 0。另外,在处理之前的index和count值之后,增加index和count,即在内部if块之后移动以下内容:
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);
}
}输出
面向对象编程是一种基于对象而不是“动作”和数据而不是逻辑的编程语言模型。噢,布拉贝拉。面向对象编程bla.
https://stackoverflow.com/questions/73938883
复制相似问题