Как удалить символ из строки java
Перейти к содержимому

Как удалить символ из строки java

  • автор:

Удалить определенные символы из строки в Java

В этом посте будет обсуждаться, как удалить определенные символы из строки в Java.

1. Использование String.replaceAll() метод

Стандартное решение для замены каждой подстроки строки, которая соответствует заданному регулярному выражению, использует метод String.replaceAll() метод.

Его можно использовать для удаления определенных символов из строки, как показано ниже. Следующий код заменяет все совпадения регулярного выражения \w с пустой строкой «» . Обратите внимание, что \w это предопределенный класс символов, который обозначает словесный символ [a-zA-Z_0-9] .

Как удалить символ в строке

Так строки в Java неизменяемы, нет прямого функционала удалить символ в строке. Но для решения этой проблемы можно создать новую строку без этого символа.

Как удалить символ в строке

Так как строки в Java иммутабельны, нам придётся сконструировать новую строку из старой.

Допустим, у нас есть строка «Hello wWorld!», и нам нужно удалить лишнюю букву «w»:

Для этого сначала найдём позицию символа «w»:

Символ «w» находится на шестой позиции в искомой строке. Затем сконструируем новую строку с помощью метода substring:

Здесь мы создали новую строку из искомой строки, скопировав взяв из искомой строки все символы до «w» и символы после «w»:

How to Remove Character from String in Java

Sometimes we have to remove characters from a String in Java. There is no remove() method in String class to do this.

Table of Contents

Java Remove Character from String

Java String class has various replace() methods. We can use this to remove characters from a string. The idea is to pass an empty string as a replacement.

Let’s look at the replace() methods present in the String class.

  1. replace( char oldChar, char newChar) : This method returns a new string where oldChar is replaced with newChar. This method replaces all the occurrences of the oldChar with the newChar character.
  2. replace(CharSequence target, CharSequence replacement) : This method replaces the target substring with the replacement substring. This method replaces all the matches of target substring with the replacement substring.
  3. replaceFirst(String regex, String replacement) : This method replaces the first match of the regex with the replacement string. This method is useful when we have to replace only the first occurrence of the substring.
  4. replaceAll(String regex, String replacement) : It’s like the replaceFirst() method. The only difference is that all the occurrences of the matched regex are replaced with the replacement string.

NOTE: There is no empty character constant. So we can’t use the first replace(char c1, char c2) method to remove a character from the string. We will have to use any of the other three methods by passing an empty string as a replacement.

Java String Replace Empty Character Error

Java String Replace Empty Character Compiler Error

Java Remove Character from String Example

Let’s look at a simple example to remove all occurrences of a character from the string.

Java String Remove Character Example

Java String Remove Character Example

Java Remove Substring from String Example

Let’s look at an example to remove a substring from the string.

Java Remove Substring Regex Example

The replaceFirst() and replaceAll() methods accept regular expression as the first argument. We can use it to remove a pattern from the string. For example, remove all the lowercase characters from the string.

Remove Whitespaces from the String

Let’s look at an example to remove all the whitespaces from the string.

What if the string has tab-character?

Let’s see how to remove tab-character and whitespaces from the string.

We can also use regex for this.

How to Remove the Last Character from the String?

There is no method to remove the last character from the string. We can achieve this using substring() method.

Conclusion

We don’t need remove() method to remove characters from the string. The replace() methods are good enough for this task.

Class String

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

is equivalent to:

Here are some more examples of how strings can be used:

The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String .

The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).

Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator class provides methods for finer-grain, locale-sensitive String comparison.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *