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

от admin

How To Remove a Character from a String in Java

In this article, you’ll learn a few different ways to remove a character from a String object in Java. Although the String class doesn’t have a remove() method, you can use variations of the replace() method and the substring() method to remove characters from strings.

Note: String objects are immutable, which means that they can’t be changed after they’re created. All of the String class methods described in this article return a new String object and do not change the original object. The type of string you use depends on the requirements of your program. Learn more about other types of string classes and why strings are immutable in Java.

The String class has the following methods that you can use to replace or remove characters:

  • replace(char oldChar, char newChar) : Returns a new String object that replaces all of the occurrences of oldChar in the given string with newChar . You can also use the replace() method, in the format replace(CharSequence target, CharSequence replacement) , to return a new String object that replaces a substring in the given string.
  • replaceFirst(String regex, String replacement) : Returns a new String object that replaces the first substring that matches the regular expression in the given string with the replacement.
  • replaceAll(String regex, String replacement) : Returns a new String object that replaces each substring that matches the regular expression in the given string with the replacement.
  • substring(int start, int end) : Returns a new String object that contains a subsequence of characters currently contained in this sequence. The substring begins at the specified start and extends to the character at index end minus 1.

Notice that the first argument for the replaceAll() and replaceFirst() methods is a regular expression. You can use a regular expression to remove a pattern from a string.

Note: You need to use double quotes to indicate literal string values when you use the replace() methods. If you use single quotes, then the JRE assumes you’re indicating a character constant and you’ll get an error when you compile the program.

Remove a Character from a String in Java

You can remove all instances of a character from a string in Java by using the replace() method to replace the character with an empty string. The following example code removes all of the occurrences of lowercase “ a ” from the given string:

Remove Spaces from a String in Java

You can remove spaces from a string in Java by using the replace() method to replace the spaces with an empty string. The following example code removes all of the spaces from the given string:

Remove a Substring from a String in Java

You can remove only the first occurrence of a character or substring from a string in Java by using the replaceFirst() method to replace the character or substring with an empty string. The following example code removes the first occurrence of “ ab ” from the given string:

Remove all the Lowercase Letters from a String in Java

You can use a regular expression to remove characters that match a given pattern from a string in Java by using the replace.All() method to replace the characters with an empty string. The following example code removes all of the lowercase letters from the given string:

Remove the Last Character from a String in Java

There is no specific method to replace or remove the last character from a string, but you can use the String substring() method to truncate the string. The following example code removes the last character from the given string:

Try it out

The following example file defines a class that includes all of the method examples provided in this article, and prints out the results after invoking each method on the given string. You can use this example code to try it out yourself on different strings using different matching patterns and replacement values.

If you have Java installed, you can create a new file called JavaStringRemove.java and add the following code to the file:

Compile and run the program:

You get the following output:

Each method in the JavaStringRemove example class operates on the given string. The output shows that the characters specified in each method have been removed from the string.

Читать:
Почему ноутбук не видит wifi с телефона айфон

Conclusion

In this article you learned various ways to remove characters from strings in Java using methods from the String class, including replace() , replaceAll() , replaceFirst() , and substring() . Continue your learning with more Java tutorials.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Программирование на C, C# и Java

Уроки программирования, алгоритмы, статьи, исходники, примеры программ и полезные советы

ОСТОРОЖНО МОШЕННИКИ! В последнее время в социальных сетях участились случаи предложения помощи в написании программ от лиц, прикрывающихся сайтом vscode.ru. Мы никогда не пишем первыми и не размещаем никакие материалы в посторонних группах ВК. Для связи с нами используйте исключительно эти контакты: vscoderu@yandex.ru, https://vk.com/vscode

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

В языке Java для строковых полей типа String отсутствует метод удаления символа с указанным индексом (в C# это метод Remove). Поэтому, чтобы произвести удаление символа из строки в Java нужно пойти на некоторые ухищрения. Рассмотрим в данном уроке один из таких способов.

Удаление символа с помощью комбинации методов substring

В Java у строк есть метод substring(int startIndex, int endIndex), который возвращает подстроку из исходной строки с позиции startIndex (включительно) до endIndex (не включительно). Нумерация индексов начинается с нуля.

С помощью данного метода извлечём из исходной строки две подстроки до и после удаляемого элемента (его индекс обозначим, как deletePosition) и соединим их в одну. Тем самым в новой строке будет отсутствовать символ с индексом deletePosition.

StringBuilder

Строки в Java — это неизменяемые объекты (immutable). Так было сделано для того, чтобы класс-строку можно было сильно оптимизировать и использовать повсеместно. Например, в качестве ключей у коллекции HashMap рекомендуется использовать только immutable-типы.

Однако часто возникают ситуации, когда программисту все же было бы удобнее иметь String -класс, который можно менять. Который не создает новую подстроку при каждом вызове его метода.

Например, у нас есть очень большая строка и мы часто дописываем что-то в ее конец. В этом случае даже коллекция символов ( ArrayList<Character> ) может быть эффективнее, чем постоянное пересоздание строк и конкатенации объектов типа String .

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

Создание объекта

Чтобы создать объект StringBuilder на основе существующей строки, нужно выполнить команду вида:

Чтобы создать пустую изменяемую строку, нужно воспользоваться командой вида:

Класс StringBuilder имеет два десятка полезных методов, вот самые важные из них:

Метод Описание
Преобразовывает переданный объект в строку и добавляет к текущей строке
Преобразовывает переданный объект в строку и вставляет в текущую строку
Заменяет часть строки, заданную интервалом start..end на переданную строку
Удаляет из строки символ под номером index
Удаляет из строки символы, заданные интервалом
Ищет подстроку в текущей строке
Ищет подстроку в текущей строке с конца
Возвращает символ строки по его индексу
Возвращает подстроку, заданную интервалом
Разворачивает строку задом наперед.
Изменяет символ строки, заданный индексом на переданный
Возвращает длину строки в символах

Вот краткое описание каждого метода

2. Краткое описание методов

Добавление к строке

Чтобы что-то добавить к изменяемой строке ( StringBuilder ), нужно воспользоваться методом append() . Пример:

Код Описание

Преобразование к стандартной строке

Чтобы преобразовать объект StringBuilder к строке типа String, нужно просто вызвать у него метод toString() . Пример

Код Вывод на экран

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

Чтобы удалить символ в изменяемой строке, вам нужно воспользоваться методом deleteCharAt() . Пример:

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

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

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

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

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

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

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

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

Похожие статьи