Java класс string подстрока

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.
Читайте также:  Select all checkbox in java

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.

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 .

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

Источник

Класс String в Java

Java-университет

Класс String в Java - 1

Класс String в Java предназначен для работы со строками в Java. Все строковые литералы, определенные в Java программе (например, «abc») — это экземпляры класса String. Давай посмотрим на его ключевые характеристики:

  1. Класс реализует интерфейсы Serializable и CharSequence . Поскольку он входит в пакет java.lang , его не нужно импортировать.
  2. Класс String в Java — это final класс, который не может иметь потомков.
  3. Класс String — immutable класс, то есть его объекты не могут быть изменены после создания. Любые операции над объектом String, результатом которых должен быть объект класса String, приведут к созданию нового объекта.
  4. Благодаря своей неизменности, объекты класса String являются потокобезопасными и могут быть использованы в многопоточной среде.
  5. Каждый объект в Java может быть преобразован в строку через метод toString , унаследованный всеми Java-классами от класса Object .

Работа с Java String

Это один из самых часто используемых классов в Java. В нем есть методы для анализа определенных символов строки, для сравнения и поиска строк, извлечения подстрок, создания копии строки с переводом всех символов в нижний и верхний регистр и прочие. Список всех методов класса String можно изучить в официальной документации. Также в Java реализован несложный механизм конкатенации (соединения строк), преобразования примитивов в строку и наоборот. Давай рассмотрим некоторые примеры работы с классом String в Java.

Создание строк

  • создать объект, содержащий пустую строку
  • создать копию строковой переменной
  • создать строку на основе массива символов
  • создать строку на основе массива байтов (с учетом кодировок)
  • и т.д.

Сложение строк

Сложить две строки в Java довольно просто, воспользовавшись оператором + . Java позволяет складывать друг с другом и переменные, и строковые литералы:

 public static void main(String[] args)

Складывая объекты класса String с объектами других классов, мы приводим последние к строковому виду. Преобразование объектов других классов к строковому представлению выполняется через неявный вызов метода toString у объекта. Продемонстрируем это на следующем примере:

 public class StringExamples < public static void main(String[] args) < Human max = new Human("Макс"); String out = "Java объект: " + max; System.out.println(out); // Вывод: Java объект: Человек с именем Макс >static class Human < private String name; public Human(String name) < this.name = name; >@Override public String toString() < return "Человек с именем " + name; >> > 

Сравнение строк

 public static void main(String[] args) < String x = "Test String"; System.out.println("Test String".equals(x)); // true >
 public static void main(String[] args) < String x = "Test String"; System.out.println("test string".equalsIgnoreCase(x)); // true >

Перевод объекта/примитива в строку

Для перевода экземпляра любого Java-класса или любого примитивного типа данных к строковому представлению, можно использовать метод String.valueOf() :

 public class StringExamples < public static void main(String[] args) < String a = String.valueOf(1); String b = String.valueOf(12.0D); String c = String.valueOf(123.4F); String d = String.valueOf(123456L); String s = String.valueOf(true); String human = String.valueOf(new Human("Alex")); System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(d); System.out.println(s); System.out.println(human); /* Вывод: 1 12.0 123.4 123456 true Человек с именем Alex */ >static class Human < private String name; public Human(String name) < this.name = name; >@Override public String toString() < return "Человек с именем " + name; >> > 

Перевод строки в число

Часто бывает нужно перевести строку в число. У классов оберток примитивных типов есть методы, которые служат как раз для этой цели. Все эти методы начинаются со слова parse. Рассмотрим ниже перевод строки в целочисленное ( Integer ) и дробное ( Double ) числа:

 public static void main(String[] args) < Integer i = Integer.parseInt("12"); Double d = Double.parseDouble("12.65D"); System.out.println(i); // 12 System.out.println(d); // 12.65 >

Перевод коллекции строк к строковому представлению

  • join(CharSequence delimiter, CharSequence. elements)
  • join(CharSequence delimiter, Iterable elements)
 public static void main(String[] args) < Listpeople = Arrays.asList( "Philip J. Fry", "Turanga Leela", "Bender Bending Rodriguez", "Hubert Farnsworth", "Hermes Conrad", "John D. Zoidberg", "Amy Wong" ); String peopleString = String.join("; ", people); System.out.println(peopleString); /* Вывод: Philip J. Fry; Turanga Leela; Bender Bending Rodriguez; Hubert Farnsworth; Hermes Conrad; John D. Zoidberg; Amy Wong */ > 

Разбиение строки на массив строк

Эту операцию выполняет метод split(String regex) В качестве разделителя выступает строковое регулярное выражение regex . В примере ниже произведем операцию, обратную той, что мы выполняли в предыдущем примере:

 public static void main(String[] args) < String people = "Philip J. Fry; Turanga Leela; Bender Bending Rodriguez; Hubert Farnsworth; Hermes Conrad; John D. Zoidberg; Amy Wong"; String[] peopleArray = people.split("; "); for (String human : peopleArray) < System.out.println(human); >/* Вывод: Philip J. Fry Turanga Leela Bender Bending Rodriguez Hubert Farnsworth Hermes Conrad John D. Zoidberg Amy Wong */ > 

Определение позиции элемента в строке

  1. indexOf(int ch)
  2. indexOf(int ch, int fromIndex)
  3. indexOf(String str)
  4. indexOf(String str, int fromIndex)
  5. lastIndexOf(int ch)
  6. lastIndexOf(int ch, int fromIndex)
  7. lastIndexOf(String str)
  8. lastIndexOf(String str, int fromIndex)
  1. ch — искомый символ ( char )
  2. str — искомая строка
  3. fromIndex — позиция с которой нужно искать элемент
  4. методы indexOf — возвращают позицию первого найденного элемента
  5. методы lastIndexOf — возвращают позицию последнего найденного элемента
 public static void main(String[] args) < String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; System.out.println(alphabet.indexOf('A')); // 0 System.out.println(alphabet.indexOf('K')); // 10 System.out.println(alphabet.indexOf('Z')); // 25 System.out.println(alphabet.indexOf('Я')); // -1 >

Извлечение подстроки из строки

 public static void main(String[] args) < String filePath = "D:\\Movies\\Futurama.mp4"; int lastFileSeparatorIndex = filePath.lastIndexOf('\\'); String fileName = filePath.substring(lastFileSeparatorIndex + 1); System.out.println(fileName); //9 >

Перевод строки в верхний/нижний регистр:

 public static void main(String[] args) < String fry = "Philip J. Fry"; String lowerCaseFry = fry.toLowerCase(); String upperCaseFry = fry.toUpperCase(); System.out.println(lowerCaseFry); // philip j. fry System.out.println(upperCaseFry); // PHILIP J. FRY >
  • Знакомство со String приводится на 1-ом уровне, 4-ой лекции квеста Java Syntax
  • Внутреннее устройство String, метод substring изучаются на 2-ом уровне, 3-ей лекции квеста Java Multithreading
  • Поиск, получение, удаление подстроки в String изучаются на 2-ом уровне, 4-ой лекции квеста Java Multithreading
  • Метод String.format рассматривается на 2-ом уровне, 6-ой лекции квеста Java Multithreading

Дополнительные источники

  1. Строки в Java — статья раскрывает некоторые основы по работе со строками в Java.
  2. Java String. Вопросы к собеседованию и ответы на них, ч.1 — в данной статье рассматриваются вопросы к собеседованию по теме String , а также даются ответы на вопросы с пояснениями и примерами кода.
  3. Строки в Java (class java.lang.String) — в данной статье приводится более глубокий разбор класса String, а также рассматриваются тонкости работы с этим классом.

Источник

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