Manipulating Characters in a String
The String class has a number of methods for examining the contents of strings, finding characters or substrings within a string, changing case, and other tasks.
Getting Characters and Substrings by Index
You can get the character at a particular index within a string by invoking the charAt() accessor method. The index of the first character is 0, while the index of the last character is length()-1 . For example, the following code gets the character at index 9 in a string:
Indices begin at 0, so the character at index 9 is 'O', as illustrated in the following figure:
If you want to get more than one consecutive character from a string, you can use the substring method. The substring method has two versions, as shown in the following table:
| Method | Description |
|---|---|
| String substring(int beginIndex, int endIndex) | Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex — 1 . |
| String substring(int beginIndex) | Returns a new string that is a substring of this string. The integer argument specifies the index of the first character. Here, the returned substring extends to the end of the original string. |
The following code gets from the Niagara palindrome the substring that extends from index 11 up to, but not including, index 15, which is the word "roar":
Other Methods for Manipulating Strings
Here are several other String methods for manipulating strings:
| Method | Description |
|---|---|
| String[] split(String regex) String[] split(String regex, int limit) |
Searches for a match as specified by the string argument (which contains a regular expression) and splits this string into an array of strings accordingly. The optional integer argument specifies the maximum size of the returned array. Regular expressions are covered in the lesson titled "Regular Expressions." |
| CharSequence subSequence(int beginIndex, int endIndex) | Returns a new character sequence constructed from beginIndex index up until endIndex — 1. |
| String trim() | Returns a copy of this string with leading and trailing white space removed. |
| String toLowerCase() String toUpperCase() |
Returns a copy of this string converted to lowercase or uppercase. If no conversions are necessary, these methods return the original string. |
Searching for Characters and Substrings in a String
Here are some other String methods for finding characters or substrings within a string. The String class provides accessor methods that return the position within the string of a specific character or substring: indexOf() and lastIndexOf() . The indexOf() methods search forward from the beginning of the string, and the lastIndexOf() methods search backward from the end of the string. If a character or substring is not found, indexOf() and lastIndexOf() return -1.
The String class also provides a search method, contains , that returns true if the string contains a particular character sequence. Use this method when you only need to know that the string contains a character sequence, but the precise location isn't important.
The following table describes the various string search methods.
| Method | Description |
|---|---|
| int indexOf(int ch) int lastIndexOf(int ch) |
Returns the index of the first (last) occurrence of the specified character. |
| int indexOf(int ch, int fromIndex) int lastIndexOf(int ch, int fromIndex) |
Returns the index of the first (last) occurrence of the specified character, searching forward (backward) from the specified index. |
| int indexOf(String str) int lastIndexOf(String str) |
Returns the index of the first (last) occurrence of the specified substring. |
| int indexOf(String str, int fromIndex) int lastIndexOf(String str, int fromIndex) |
Returns the index of the first (last) occurrence of the specified substring, searching forward (backward) from the specified index. |
| boolean contains(CharSequence s) | Returns true if the string contains the specified character sequence. |
Replacing Characters and Substrings into a String
The String class has very few methods for inserting characters or substrings into a string. In general, they are not needed: You can create a new string by concatenation of substrings you have removed from a string with the substring that you want to insert.
The String class does have four methods for replacing found characters or substrings, however. They are:
| Method | Description |
|---|---|
| String replace(char oldChar, char newChar) | Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. |
| String replace(CharSequence target, CharSequence replacement) | Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. |
| String replaceAll(String regex, String replacement) | Replaces each substring of this string that matches the given regular expression with the given replacement. |
| String replaceFirst(String regex, String replacement) | Replaces the first substring of this string that matches the given regular expression with the given replacement. |
An Example
The following class, Filename , illustrates the use of lastIndexOf() and substring() to isolate different parts of a file name.
Here is a program, FilenameDemo , that constructs a Filename object and calls all of its methods:
And here's the output from the program:
As shown in the following figure, our extension method uses lastIndexOf to locate the last occurrence of the period (.) in the file name. Then substring uses the return value of lastIndexOf to extract the file name extension — that is, the substring from the period to the end of the string. This code assumes that the file name has a period in it; if the file name does not have a period, lastIndexOf returns -1, and the substring method throws a StringIndexOutOfBoundsException .
Also, notice that the extension method uses dot + 1 as the argument to substring . If the period character (.) is the last character of the string, dot + 1 is equal to the length of the string, which is one larger than the largest index into the string (because indices start at 0). This is a legal argument to substring because that method accepts an index equal to, but not greater than, the length of the string and interprets it to mean "the end of the string."
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.
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

Соединение строк
Для соединения строк можно использовать операцию сложения («+»):
При этом если в операции сложения строк используется нестроковый объект, например, число, то этот объект преобразуется к строке:
Фактически же при сложении строк с нестроковыми объектами будет вызываться метод valueOf() класса String. Данный метод имеет множество перегрузок и преобразует практически все типы данных к строке. Для преобразования объектов различных классов метод valueOf вызывает метод toString() этих классов.
Другой способ объединения строк представляет метод concat() :
Метод concat() принимает строку, с которой надо объединить вызывающую строку, и возвращает соединенную строку.
Еще один метод объединения — метод join() позволяет объединить строки с учетом разделителя. Например, выше две строки сливались в одно слово «HelloJava», но в идеале мы бы хотели, чтобы две подстроки были разделены пробелом. И для этого используем метод join() :
Метод join является статическим. Первым параметром идет разделитель, которым будут разделяться подстроки в общей строке, а все последующие параметры передают через запятую произвольный набор объединяемых подстрок — в данном случае две строки, хотя их может быть и больше
Извлечение символов и подстрок
Для извлечения символов по индексу в классе String определен метод char charAt(int index) . Он принимает индекс, по которому надо получить символов, и возвращает извлеченный символ:
Как и в массивах индексация начинается с нуля.
Если надо извлечь сразу группу символов или подстроку, то можно использовать метод getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) . Он принимает следующие параметры:
srcBegin : индекс в строке, с которого начинается извлечение символов
srcEnd : индекс в строке, до которого идет извлечение символов
dst : массив символов, в который будут извлекаться символы
dstBegin : индекс в массиве dst, с которого надо добавлять извлеченные из строки символы
Сравнение строк
Для сравнения строк используются методы equals() (с учетом регистра) и equalsIgnoreCase() (без учета регистра). Оба метода в качестве параметра принимают строку, с которой надо сравнить:
В отличие от сравнения числовых и других данных примитивных типов для строк не применяется знак равенства ==. Вместо него надо использовать метод equals() .
Еще один специальный метод regionMatches() сравнивает отдельные подстроки в рамках двух строк. Он имеет следующие формы:
Метод принимает следующие параметры:
ignoreCase : надо ли игнорировать регистр символов при сравнении. Если значение true , регистр игнорируется
toffset : начальный индекс в вызывающей строке, с которого начнется сравнение
other : строка, с которой сравнивается вызывающая
oofset : начальный индекс в сравниваемой строке, с которого начнется сравнение
len : количество сравниваемых символов в обеих строках
В данном случае метод сравнивает 3 символа с 6-го индекса первой строки («wor») и 3 символа со 2-го индекса второй строки («wor»). Так как эти подстроки одинаковы, то возвращается true .
И еще одна пара методов int compareTo(String str) и int compareToIgnoreCase(String str) также позволяют сравнить две строки, но при этом они также позволяют узнать больше ли одна строка, чем другая или нет. Если возвращаемое значение больше 0, то первая строка больше второй, если меньше нуля, то, наоборот, вторая больше первой. Если строки равны, то возвращается 0.
Для определения больше или меньше одна строка, чем другая, используется лексикографический порядок. То есть, например, строка «A» меньше, чем строка «B», так как символ ‘A’ в алфавите стоит перед символом ‘B’. Если первые символы строк равны, то в расчет берутся следующие символы. Например:
Поиск в строке
Метод indexOf() находит индекс первого вхождения подстроки в строку, а метод lastIndexOf() — индекс последнего вхождения. Если подстрока не будет найдена, то оба метода возвращают -1:
Метод startsWith() позволяют определить начинается ли строка с определенной подстроки, а метод endsWith() позволяет определить заканчивается строка на определенную подстроку:
Замена в строке
Метод replace() позволяет заменить в строке одну последовательность символов на другую:
Обрезка строки
Метод trim() позволяет удалить начальные и конечные пробелы:
Метод substring() возвращает подстроку, начиная с определенного индекса до конца или до определенного индекса:
Изменение регистра
Метод toLowerCase() переводит все символы строки в нижний регистр, а метод toUpperCase() — в верхний:
Split
Метод split() позволяет разбить строку на подстроки по определенному разделителю. Разделитель — какой-нибудь символ или набор символов передается в качестве параметра в метод. Например, разобьем текст на отдельные слова:
Remove Substring From String in Java

In this tutorial, we will learn how to remove a substring from any given string in Java.
Please enable JavaScript
replace() Method to Remove Substring in Java
The first and most commonly used method to remove/replace any substring is the replace() method of Java String class.
The first parameter is the substring to be replaced, and the second parameter is the new substring to replace the first parameter.
StringBuffer.replace() Method to Remove Character From String in Java
This method could remove/replace any substring in the given index range. Java StringBuffer is similar to String , but is mutable.
The syntax of StringBuffer.replace() method is,
start and end are the beginning and ending index of the specified range. start is inclusive, and end is exclusive; therefore, the actual range is [start, end-1] .
str is the string that replaces the content in the above-specified range.
replaceAll() Method to Remove Substring From String in Java
Another similar method to replace() method is to use replaceAll() method of Java String class.
regex is the pattern of the regular expression.
replace is the string to replace the existing one.
A more enhanced point to use the replaceAll() method is to use a pattern of the regular expression to remove substrings that match the pattern all at once.