Java получить часть строки до символа

Подробно про Substring в Java

Метод подстроки String очень полезен в программировании Core Java. Это фундаментальный метод выполнения операций со строками. Substring извлекает последовательность символов из String и возвращает ее как новый объект String.

У метода Substring есть два варианта. Первый принимает только один аргумент, а другой – два.

Подстрока (int beginIndex)

Этот метод вернет новый объект String, содержащий подстроку данной строки из указанного startIndex (включительно). Это получит часть String, начинающуюся с заданного beginIndex и до последнего символа String.

public String substring(int beginIndex)

где beginIndex – индекс, с которого начать извлечение возвращаемой подстроки (включительно)
Ключевая идея состоит в том, что он получит все символы из индекса, указанного в beginIndex, до последнего символа в строке.

Например, если у нас есть строка «ABCDE», символ в индексе 2 будет «C». Следовательно, «ABCDE» .substring (2) вернет все символы от «C» до «E», что является строкой «CDE».

Пример использования Substring в Java

public class SubstringTest < public static void main(String[] args) < String testString = "ABCDEFGHIJ"; System.out.println(testString.substring(0)); System.out.println(testString.substring(1)); System.out.println(testString.substring(2)); System.out.println(testString.substring(3)); System.out.println(testString.substring(4)); System.out.println(testString.substring(5)); System.out.println(testString.substring(6)); System.out.println(testString.substring(7)); System.out.println(testString.substring(8)); System.out.println(testString.substring(9)); >>

А вот вывод приведенного выше кода.

ABCDEFGHIJ BCDEFGHIJ CDEFGHIJ DEFGHIJ EFGHIJ FGHIJ GHIJ HIJ IJ J

substring(int beginIndex, int endIndex)

Этот метод вернет новый объект String, содержащий подстроку данной строки от указанного startIndex до endIndex. И получит часть String, начиная с данного beginIndex и до указанного endIndex.

public String substring(int beginIndex, int endIndex)

где beginIndex – индекс, с которого нужно начать извлечение возвращаемой подстроки. (включительно)
endIndex – индекс, с которого нужно закончить извлечение возвращаемой подстроки. (эксклюзив)

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

Помните также, что beginIndex является включающим, а endIndex – эксклюзивным. Например, символ в индексе 2 строки «ABCDE» – это «C», а символ в индексе 4 – «E». Возвращенная строка будет содержать символы от «C» включительно до символа «E» (то есть мы не включаем E). Результат – “CD”.

public class SubstringTest < public static void main(String[] args) < String testString = "ABCDEFGHIJ"; System.out.println(testString.substring(0,5)); System.out.println(testString.substring(1,5)); System.out.println(testString.substring(2,5)); System.out.println(testString.substring(0,6)); System.out.println(testString.substring(1,6)); System.out.println(testString.substring(2,6)); System.out.println(testString.substring(0,7)); System.out.println(testString.substring(1,7)); System.out.println(testString.substring(2,7)); >>
ABCDE BCDE CDE ABCDEF BCDEF CDEF ABCDEFG BCDEFG CDEFG

Вот пример программы, которая примет строку и распечатает все возможные подстроки.

import java.util.Scanner; public class PrintAllSubstring < public static void main(String[] args) < System.out.println("Enter a string:"); Scanner in = new Scanner(System.in); String inputString = in.nextLine(); for (int beginIndex = 0; beginIndex < inputString.length(); beginIndex++) < for (int endIndex = beginIndex + 1; endIndex > > >

И вот результат, предполагающий, что была введена строка wxyz.

Enter a string: wxyz w wx wxy wxyz x xy xyz y yz z

Вот пример того, как получить середину строки с помощью метода substring в алгоритме.

public class MiddleStrTest < public static void main(String[] args) < System.out.println("A -->" + getMiddleString("A")); System.out.println("AB --> " + getMiddleString("AB")); System.out.println("ABC --> " + getMiddleString("ABC")); System.out.println("ABCD --> " + getMiddleString("ABCD")); System.out.println("ABCDE --> " + getMiddleString("ABCDE")); System.out.println("ABCDEF --> " + getMiddleString("ABCDEF")); System.out.println("ABCDEFG --> " + getMiddleString("ABCDEFG")); > private static String getMiddleString(String str) < if (str.length() int beginIndex = (str.length() - 1) / 2; int endIndex = beginIndex + 2 - (str.length() % 2); return str.substring(beginIndex, endIndex); > >
A --> A AB --> AB ABC --> B ABCD --> BC ABCDE --> C ABCDEF --> CD ABCDEFG --> D

Вот пример программы, которая перевернет строку.

public class ReverseTest < public static void main(String[] args) < System.out.println(reverse("ABCDEFG")); >private static String reverse(String str) < if (str.length() return reverse(str.substring(1)) + str.substring(0, 1); > >

Это выведет обратную строку ABCDEFG:
GFEDCBA
Вот пример программы, которая проверит, является ли строка палиндромом или нет.

public class PalTest < public static void main(String[] args) < System.out.println(palindrome("ABCBA")); System.out.println(palindrome("ABCCBA")); System.out.println(palindrome("ABCCXA")); System.out.println(palindrome("ABCDEFG")); >private static boolean palindrome(String str) < if (str.length() String first = str.substring(0, 1); String last = str.substring(str.length() - 1); return first.equals(last) && palindrome(str.substring(1, str.length() - 1)); > >

Средняя оценка 5 / 5. Количество голосов: 1

Читайте также:  File control in html

Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.

Видим, что вы не нашли ответ на свой вопрос.

Напишите комментарий, что можно добавить к статье, какой информации не хватает.

Источник

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:

String anotherPalindrome = "Niagara. O roar again!"; char aChar = anotherPalindrome.charAt(9);

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:

The substring Methods in the String Class

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»:

String anotherPalindrome = "Niagara. O roar again!"; String roar = anotherPalindrome.substring(11, 15);

Other Methods for Manipulating Strings

Here are several other String methods for manipulating strings:

Other Methods in the String Class 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.

Читайте также:  Learn django and python

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.

The Search Methods in the String Class

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.

Note: CharSequence is an interface that is implemented by the String class. Therefore, you can use a string as an argument for the contains() method.

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:

Methods in the String Class for Manipulating Strings

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.

Note: The methods in the following Filename class don’t do any error checking and assume that their argument contains a full directory path and a filename with an extension. If these methods were production code, they would verify that their arguments were properly constructed.

public class Filename < private String fullPath; private char pathSeparator, extensionSeparator; public Filename(String str, char sep, char ext) < fullPath = str; pathSeparator = sep; extensionSeparator = ext; >public String extension() < int dot = fullPath.lastIndexOf(extensionSeparator); return fullPath.substring(dot + 1); >// gets filename without extension public String filename() < int dot = fullPath.lastIndexOf(extensionSeparator); int sep = fullPath.lastIndexOf(pathSeparator); return fullPath.substring(sep + 1, dot); >public String path() < int sep = fullPath.lastIndexOf(pathSeparator); return fullPath.substring(0, sep); >>

Here is a program, FilenameDemo , that constructs a Filename object and calls all of its methods:

public class FilenameDemo < public static void main(String[] args) < final String FPATH = "/home/user/index.html"; Filename myHomePage = new Filename(FPATH, '/', '.'); System.out.println("Extension = " + myHomePage.extension()); System.out.println("Filename = " + myHomePage.filename()); System.out.println("Path = " + myHomePage.path()); >>

And here’s the output from the program:

Extension = html Filename = index Path = /home/user

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 .

Читайте также:  Center property in html

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.»

Previous page: Converting Between Numbers and Strings
Next page: Comparing Strings and Portions of Strings

Источник

Подстрока в сроке на Java или как работает метод substring()

Строки в основном определяются как массив символов. В Java объекты String являются неизменяемыми, что означает, что константа не может быть изменена после создания.

Что такое подстрока в Java?

Часть строки называется подстрокой в Java. Другими словами, подстрока является подмножеством другой строки. Метод substring() возвращает новую строку, которая является подстрокой этой строки. Метод является перегруженным.

Синтаксис

substring (// любой из методов) 

Пример

пример подстроки

Здесь строка «Edureka», но когда вы разбиваете ее на блоки, она состоит из подстрок, которые в итоге вычисляют строку.

Методы

В основе метода substring() два основных метода. Они есть:

String substring (int begIndex)

Этот метод имеет два варианта и возвращает новую строку, которая является подстрокой этой строки. Подстрока начинается с символа по указанному индексу beginIndex до конца строки.

Синтаксис

public String substring (int begIndex)

Примечание: индекс начинается с 0, что относится к первому символу строки.

Пример

String substring​(int beginIndex, int endIndex)

Этот метод имеет два варианта и возвращает новую строку, которая является подстрокой этой строки. Подстрока начинается с символа с указанным индексом beginIndex и продолжается до конца строки или до endIndex – 1, если присутствует другой аргумент.

Синтаксис

public String substring​(int beginIndex, int endIndex)

Пример

Программа

Пример кода для печати всех подстрок заданной строки:

class Course < // Function to print all sub strings static void subString(char str[], int n) < // Pick starting point for (int len = 1; len System.out.println(); > > > // Driver program to test the above function public static void main(String[] args) < char str[] = ; subString(str, str.length); > >

вывод

Далее, используя метод substr()

public class Substring < // Function to print all substring public static void SubString(String str, int n) < for (int i = 0; i < n; i++) for (int j = i+1; j public static void main(String[] args) < String str = "abcd"; SubString(str, str.length()); >>

Источник

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