gpt4 book ai didi

java - 如何替换第N个出现的字符串?

转载 作者:行者123 更新时间:2023-11-30 05:41:13 27 4
gpt4 key购买 nike

这是我的代码:

public class Phrase {
private String currentPhrase;
public Phrase (String p) {
currentPhrase = p;
}

public int findNthOccurrence(String str, int n) {
int c = 0;
for(int i = 0; i < currentPhrase.length() - str.length(); i++) {
if(str.equals(currentPhrase.substring(i,i+str.length())))
c++;
if(c == n)
return i;
}
return -1;

}

public void replaceNthOccurence(String str, int n, String rep) {
int temp = findNthOccurrence(str,n);
if(temp == -1) {
currentPhrase = currentPhrase;
}
currentPhrase = currentPhrase.substring(0,temp+1) + rep +
currentPhrase.substring(currentPhrase.length() - rep.length(), currentPhrase.length()-1);

}
}


findNthOccurrence方法查找第n次出现的str的索引。

这是我的主要:

    Phrase phrase1 = new Phrase("A cat ate late.");
phrase1.replaceNthOccurence("at", 1, "rane");
System.out.println(phrase1);

Phrase phrase2 = new Phrase("A cat ate late.");
phrase2.replaceNthOccurence("at", 6, "xx");
System.out.println(phrase2);

Phrase phrase3 = new Phrase("A cat ate late.");
phrase3.replaceNthOccurence("bat", 2, "xx");
System.out.println(phrase3);

Phrase phrase4 = new Phrase("aaaa");
phrase4.replaceNthOccurence("aa", 1, "xx");
System.out.println(phrase4);

Phrase phrase5 = new Phrase("aaaa");
phrase5.replaceNthOccurence("aa", 2, "bbb");
System.out.println(phrase5);


当我打印出来时,我得到:

enter image description here

它应该是这样的: enter image description here

当我将其打印出来时,如何停止获取奇怪的字符并且replaceNthOccurence方法正确吗?

最佳答案

您的代码似乎正常工作。但是,问题在于您要使用对象本身。

尝试在类中实现toString,例如:

@Override
public String toString() {
return this.currentPhrase;
}


致电时:

 Phrase phrase1 = new Phrase("A cat ate late.");
phrase1.replaceNthOccurence("at", 1, "rane");
System.out.println(phrase1);


现在应该返回

A caraneate


实现toString之后。

如果您没有为您的类实现toString方法,则在打印出对象时,它将打印出类的名称,后跟一个@符号以及该对象的哈希码(以十六进制表示)。

关于java - 如何替换第N个出现的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55624662/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com