首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >替换每秒钟出现的子字符串,Java

替换每秒钟出现的子字符串,Java
EN

Stack Overflow用户
提问于 2022-10-03 17:30:29
回答 1查看 88关注 0票数 1

试图替换给定字符串“文本”中的“面向对象编程”子字符串的每一秒。我是Java的初学者,任务的目标是只使用String类方法。下面是我到目前为止想出的。预先谢谢你的帮助)

代码语言:javascript
复制
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);
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-03 18:07:26

String::replace替换了所有的事件,因此它在您的需求中的使用是不正确的。您可以使用

代码语言:javascript
复制
text = text.substring(0, index) + str2 + text.substring(index + str.length());

请注意,0 % 2==0;因此,如果您想替换发生号第二、第四、第六等等,请在内部if块中使用count % 2 != 0。另外,在处理之前的indexcount值之后,增加indexcount,即在内部if块之后移动以下内容:

代码语言:javascript
复制
count++;
index += str.length();

Demo

代码语言:javascript
复制
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.

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73938883

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档