如何替换给定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 documentation
编辑:
对不起,我误解了你的问题。这是替换第一个和最后一个除外的所有出现的示例:
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);
}
}