Jak mogę usunąć podciąg z danego ciągu?


190

Czy istnieje prosty sposób na usunięcie podciągów z danych Stringw Javie?

Przykład: "Hello World!"usuwanie "o""Hell Wrld!"

Odpowiedzi:



9

Możesz użyć StringBuffer

StringBuffer text = new StringBuffer("Hello World");
text.replace( StartIndex ,EndIndex ,String);

8

Sprawdź Apache StringUtils :

  • static String replace(String text, String searchString, String replacement) Zastępuje wszystkie wystąpienia ciągu w innym ciągu.
  • static String replace(String text, String searchString, String replacement, int max) Zastępuje ciąg innym ciągiem wewnątrz większego ciągu, dla pierwszych maksymalnych wartości szukanego ciągu.
  • static String replaceChars(String str, char searchChar, char replaceChar) Zamienia wszystkie wystąpienia znaku w ciągu na inne.
  • static String replaceChars(String str, String searchChars, String replaceChars) Zamienia wiele znaków w ciągu za jednym razem.
  • static String replaceEach(String text, String[] searchList, String[] replacementList) Zastępuje wszystkie wystąpienia ciągów w obrębie innego ciągu.
  • static String replaceEachRepeatedly(String text, String[] searchList, String[] replacementList) Zastępuje wszystkie wystąpienia ciągów w obrębie innego ciągu.
  • static String replaceOnce(String text, String searchString, String replacement) Raz zastępuje ciąg innym ciągiem w większym ciągu.
  • static String replacePattern(String source, String regex, String replacement) Zastępuje każdy podłańcuch ciągu źródłowego pasującego do podanego wyrażenia regularnego z podanym zamiennikiem za pomocą opcji Pattern.DOTALL.

1
Właśnie przetestowałem replacePattern i jest 6 razy wolniejszy niż uruchamianie niestandardowego kodu Java.
Alex Arvanitidis

6
replace('regex', 'replacement');
replaceAll('regex', 'replacement');

W twoim przykładzie

String hi = "Hello World!"
String no_o = hi.replaceAll("o", "");

4

To działa dobrze dla mnie.

String hi = "Hello World!"
String no_o = hi.replaceAll("o", "");

lub możesz użyć

String no_o = hi.replace("o", "");



1
replaceAll(String regex, String replacement)

Powyższa metoda pomoże uzyskać odpowiedź.

String check = "Hello World";
check = check.replaceAll("o","");

1

Możesz użyć Substring również do zastąpienia istniejącym łańcuchem:

var str = "abc awwwa";
var Index = str.indexOf('awwwa');
str = str.substring(0, Index);

0

Oto implementacja usuwania wszystkich podciągów z podanego ciągu

public static String deleteAll(String str, String pattern)
{
    for(int index = isSubstring(str, pattern); index != -1; index = isSubstring(str, pattern))
        str = deleteSubstring(str, pattern, index);

    return str;
}

public static String deleteSubstring(String str, String pattern, int index)
{
    int start_index = index;
    int end_index = start_index + pattern.length() - 1;
    int dest_index = 0;
    char[] result = new char[str.length()];


    for(int i = 0; i< str.length() - 1; i++)
        if(i < start_index || i > end_index)
            result[dest_index++] = str.charAt(i);

    return new String(result, 0, dest_index + 1);
}

Implementacja metody isSubstring () jest tutaj


0
private static void replaceChar() {
    String str = "hello world";
    final String[] res = Arrays.stream(str.split(""))
            .filter(s -> !s.equalsIgnoreCase("o"))
            .toArray(String[]::new);
    System.out.println(String.join("", res));
}

Jeśli masz skomplikowaną logikę do filtrowania znaku, po prostu inny sposób replace().


0

Jeśli znasz indeks początkowy i końcowy, możesz go użyć

string = string.substring(0, start_index) + string.substring(end_index, string.length());
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.