簡體   English   中英

替換字符串中的出現

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM