Заменить вхождения в строке - PullRequest
0 голосов
/ 26 января 2020

Как я могу заменить вхождения данной строки, но без первого и последнего вхождения? Входы взяты с клавиатуры. Примеры:

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') являются первым и последним.

Ответы [ 2 ]

1 голос
/ 26 января 2020

Вы можете использовать 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);
0 голосов
/ 26 января 2020
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);
    }
}
...