String java удаление символов

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

Зачастую требуется удалить первый символ в строке. Это можно сделать очень просто, используя стандартные методы класса String.

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

Так как строки в Java иммутабельны (их значение нельзя изменить), для удаления строки придётся скопировать всю строку, кроме первого символа. Это довольно тривиальная задача, которую можно решить с помощью метода substring:

String s = "!привет, мир"; String s2 = s.substring(1); System.out.println(s2);

Здесь мы объявили переменную s и присвоили ей значение «ппривет, мир». Затем, с помощью метода substring, мы создали новую строку, начиная с первой позиции. Нумерация в строке идёт с нуля, то есть нулевой позиции соответствует первый символ «!», первой позиции – второй символ «п» и так далее:

Номер позиции 0 1 2 3 4 5 6 7 8 9 10 11
Символ ! п р и в е т , м и р

Улучшенный вариант

Для создания переиспользуемого метода по удалению первого символа из строки важно добавить проверку на null и на длину строки:

Читайте также:  Python execute sql statement

public static String removeFirstChar(String s)

Это безопасный метод, который не выбросит исключение из-за того, что на вход были переданы некорректные данные. В случае, если в качестве аргумента был передан null или строка из одного символа, то на выходе будет возвращена пустая строка

Полный исходный код примера:

public class RemoveFirstCharSubstring < public static void main(String[] args) < System.out.println(removeFirstChar("!привет, мир")); >public static String removeFirstChar(String s) < return (s == null || s.length() == 0) ? "" : (s.substring(1)); >>

Заключение

С помощью метода substring можно скопировать часть исходной строки и получить новую строку. Для написания утилитарных методов важно проверять входящие данные на корректность.

Источник

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

Строки в Java являются неизменяемыми, поэтому удалить символ из строки не получится, но можно создать новую строку на основе исходной, в которой будут отсутствовать некоторые символы. Как вариант, можно воспользоваться методом строки substring​(int beginIndex, int endIndex) , который вернёт новую строку, начиная с позиции beginIndex до позиции (не включая) endIndex

"hamburger".substring(4, 8); // "urge" 

Возможна также передача в метод только одного параметра beginIndex , в этом случае метод вернёт подстроку, начиная с индекса beginIndex и до конца строки

Если нужно удалить како-то конкретный символ, можно воспользоваться методом replaceAll() . Этот метод возвращает новую строку, в которой заменяет все подстроки, которые соответствует регулярному выражению:

// Заменяем в слове подстроку "l" на пустую строку, то есть удаляем её "world".replaceAll("l", ""); // "word" 

Источник

How To Remove a Character from a String in Java

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:

String str = "abc ABC 123 abc"; String strNew = str.replace("a", ""); 

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:

String str = "abc ABC 123 abc"; String strNew = str.replace(" ", ""); 

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:

String str = "abc ABC 123 abc"; String strNew = str.replaceFirst("ab", ""); 

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:

String str = "abc ABC 123 abc"; String strNew = str.replaceAll("([a-z])", ""); 

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:

String str = "abc ABC 123 abc"; String strNew = str.substring(0, str.length()-1); 

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:

 public class JavaStringRemove  public static void main(String[] args)  String str = "abc ABC 123 abc"; // Remove a character from a string in Java System.out.println("String after removing all the 'a's = "+str.replace("a", "")); // Remove spaces from a string in Java System.out.println("String after removing all the spaces = "+str.replace(" ", "")); // Remove a substring from a string in Java System.out.println("String after removing the first 'ab' substring = "+str.replaceFirst("ab", "")); // Remove all the lowercase letters from a string in Java System.out.println("String after removing all the lowercase letters = "+str.replaceAll("([a-z])", "")); // Remove the last character from a string in Java System.out.println("String after removing the last character = "+str.substring(0, str.length()-1)); > > 

Compile and run the program:

You get the following output:

Output
String after removing all the 'a's = bc ABC 123 bc String after removing all the spaces = abcABC123abc String after removing the first 'ab' substring = c ABC 123 abc String after removing all the lowercase letters = ABC 123 String after removing the last character = abc ABC 123 ab

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.

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.

Источник

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

Java Удалить символ из строки, Удалить строку Java, Java Удалить пробелы из строки, Java удалить последний символ из строки, java удалить подстроку из строки, код java для удаления символов из строки,

Иногда нам приходится удалять символ из строки в java-программе. Но класс java String не имеет метода remove () . Итак, как бы вы этого достигли?

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

  1. заменить(char oldChar, char newChar) : Возвращает строку, полученную в результате замены всех вхождений oldChar в этой строке на newChar.
  2. заменить(цель последовательности символов, замена последовательности символов) : Заменяет каждую подстроку этой строки, соответствующую целевой последовательности литералов, указанной последовательностью замены литералов.
  3. replaceFirst(регулярное выражение строки, замена строки) : Заменяет первую подстроку этой строки, соответствующую данному регулярному выражению, на данную замену.
  4. replaceAll(регулярное выражение строки, замена строки) : Заменяет каждую подстроку этой строки, соответствующую данному регулярному выражению, данной заменой.

Итак, можем ли мы использовать заменить(‘x’,»); ? Если вы попытаетесь это сделать, вы получите ошибку компилятора как Недопустимую символьную константу . Поэтому нам придется использовать другие методы замены, которые принимают строку, потому что мы можем указать “” как пустую строку, подлежащую замене.

Пример удаления символов из строки Java

Ниже фрагмент кода показывает, как удалить все вхождения символа из данной строки.

String str = "abcdDCBA123"; String strNew = str.replace("a", ""); // strNew is 'bcdDCBA123'

Java Удаляет подстроку из строки

Давайте посмотрим, как удалить первое вхождение “ab” из строки.

String str = "abcdDCBA123"; String strNew = str.replaceFirst("ab", ""); // strNew is 'cdDCBA123'

Обратите внимание , что replaceAll и replaceFirst методы первым аргументом является регулярное выражение , мы можем использовать его для удаления шаблона из строки. Приведенный ниже фрагмент кода удалит все строчные буквы из строки.

String str = "abcdDCBA123"; String strNew = str.replaceAll("([a-z])", ""); // strNew is 'DCBA123'

Java Удаляет пробелы из строки

String str = "Hello World Java Users"; String strNew = str.replace(" ", ""); //strNew is 'HelloWorldJavaUsers'

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

Нет способа заменить или удалить последний символ из строки, но мы можем сделать это с помощью метода строковой подстроки.

String str = "Hello World!"; String strNew = str.substring(0, str.length()-1); //strNew is 'Hello World'

Строка Java Удаляет символ и Пример строки

Вот полный класс java для примеров, показанных выше.

package com.journaldev.examples; public class JavaStringRemove < public static void main(String[] args) < String str = "abcdDCBA123"; System.out.println("String after Removing 'a' = "+str.replace("a", "")); System.out.println("String after Removing First 'a' = "+str.replaceFirst("ab", "")); System.out.println("String after replacing all small letters = "+str.replaceAll("([a-z])", "")); >>

Результат, полученный вышеуказанной программой, является:

String after Removing 'a' = bcdDCBA123 String after Removing First 'a' = cdDCBA123 String after replacing all small letters = DCBA123

Это все для удаления символа или подстроки из строки в программе java.

Читайте ещё по теме:

Источник

Оцените статью