[英]Replace occurences in a String
如何替换给定字符串的出现但没有第一次出现和最后一次出现? 输入来自键盘。 例子 :
INPUT: "a creature is a small part of a big world"
a
the
OUTPUT: "a creature is the small part of a big world"
另一个例子:
INPUT: "a creature is a small part"
a
the
OUTPUT: "a creature is a small part"
在最后一个字符串中保持不变,因为两个出现(即字符“a”)都是第一个和最后一个。
您可以使用String.replaceFirst(String, String)
:
String a = "a creature is a small part of a big world";
String b = "a";
String c = "the";
String d = a.replaceFirst(" " + b + " ", " " + c + " ");
System.out.println(d);
...打印出来:
a creature is the small part of a big world
阅读文档了解更多信息: 字符串文档
编辑:
对不起,我误解了你的问题。 以下是替换除第一个和最后一个之外的所有出现的示例:
String a = "a creature is a small part of a big world";
String b = "a";
String c = "the";
String[] array = a.split(" ");
ArrayList<Integer> occurrences = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
if (array[i].equals(b)) {
occurrences.add(i);
}
}
if (occurrences.size() > 0) {
occurrences.remove(0);
}
if (occurrences.size() > 0) {
occurrences.remove(occurrences.size() - 1);
}
for (int occurrence : occurrences) {
array[occurrence] = c;
}
a = String.join(" ", array);
System.out.println(a);
编辑:
使用事件集合的替代类型:
String a = "a creature is a small part of a big world";
String b = "a";
String c = "the";
String[] array = a.split(" ");
Deque<Integer> occurrences = new ArrayDeque<>();
for (int i = 0; i < array.length; i++) {
if (array[i].equals(b)) {
occurrences.add(i);
}
}
occurrences.pollFirst();
occurrences.pollLast();
for (int occurrence : occurrences) {
array[occurrence] = c;
}
String d = String.join(" ", array);
System.out.println(d);
package com.example.functional;
import java.util.Arrays;
import java.util.List;
import java.util.function.UnaryOperator;
public class StringReplacementDemo {
public static void appendString(String str){
System.out.print(" "+str);
}
/**
* @param str1
* @param output2
* @param input
*/
public static void replaceStringExceptFistAndLastOccerance(String str1, String input, String output2) {
List<String> list = Arrays.asList(str1.split(" "));
int index = list.indexOf(input);
int last = list.lastIndexOf(input);
UnaryOperator<String> operator = t -> {
if (t.equals(input)) {
return output2;
}
return t;
};
list.replaceAll(operator);
list.set(index, input);
list.set(last, input);
list.forEach(MainClass::appendString);
}
public static void main(String[] args) {
String str1 = "a creature is a small part";
String input = "a";
String output ="the";
replaceStringExceptFistAndLastOccerance(str1,input,output);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.