Тип данных string java

Strings

Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

Creating Strings

The most direct way to create a string is to write:

String greeting = "Hello world!";

In this case, «Hello world!» is a string literal—a series of characters in your code that is enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler creates a String object with its value—in this case, Hello world! .

As with any other object, you can create String objects by using the new keyword and a constructor. The String class has thirteen constructors that allow you to provide the initial value of the string using different sources, such as an array of characters:

char[] helloArray = < 'h', 'e', 'l', 'l', 'o', '.' >; String helloString = new String(helloArray); System.out.println(helloString);

The last line of this code snippet displays hello .

Note: The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.

String Length

Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object. After the following two lines of code have been executed, len equals 17:

String palindrome = "Dot saw I was Tod"; int len = palindrome.length();

A palindrome is a word or sentence that is symmetric—it is spelled the same forward and backward, ignoring case and punctuation. Here is a short and inefficient program to reverse a palindrome string. It invokes the String method charAt(i) , which returns the i th character in the string, counting from 0.

public class StringDemo < public static void main(String[] args) < String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); char[] tempCharArray = new char[len]; char[] charArray = new char[len]; // put original string in an // array of chars for (int i = 0; i < len; i++) < tempCharArray[i] = palindrome.charAt(i); >// reverse array of chars for (int j = 0; j < len; j++) < charArray[j] = tempCharArray[len - 1 - j]; >String reversePalindrome = new String(charArray); System.out.println(reversePalindrome); > >

Running the program produces this output:

Читайте также:  Iframe css center align

To accomplish the string reversal, the program had to convert the string to an array of characters (first for loop), reverse the array into a second array (second for loop), and then convert back to a string. The String class includes a method, getChars() , to convert a string, or a portion of a string, into an array of characters so we could replace the first for loop in the program above with

palindrome.getChars(0, len, tempCharArray, 0);

Concatenating Strings

The String class includes a method for concatenating two strings:

This returns a new string that is string1 with string2 added to it at the end.

You can also use the concat() method with string literals, as in:

"My name is ".concat("Rumplestiltskin");

Strings are more commonly concatenated with the + operator, as in

The + operator is widely used in print statements. For example:

String string1 = "saw I was "; System.out.println("Dot " + string1 + "Tod");

Such a concatenation can be a mixture of any objects. For each object that is not a String , its toString() method is called to convert it to a String .

Note: The Java programming language does not permit literal strings to span lines in source files, so you must use the + concatenation operator at the end of each line in a multi-line string. For example:

String quote = "Now is the time for all good " + "men to come to the aid of their country.";

Breaking strings between lines using the + concatenation operator is, once again, very common in print statements.

Creating Format Strings

You have seen the use of the printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format() , that returns a String object rather than a PrintStream object.

Using String’s static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of

System.out.printf("The value of the float " + "variable is %f, while " + "the value of the " + "integer variable is %d, " + "and the string is %s", floatVar, intVar, stringVar);
String fs; fs = String.format("The value of the float " + "variable is %f, while " + "the value of the " + "integer variable is %d, " + " and the string is %s", floatVar, intVar, stringVar); System.out.println(fs);

Источник

Класс 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 .
Читайте также:  Bshaffer oauth2 server php

Работа с 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
Читайте также:  Python timezone by city name

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

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

Источник

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