15.11. Java – Метод getChars()
Метод getChars() – копирует символы из данной строки в массив символов назначения.
Синтаксис
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Параметры
Подробная информация о параметрах:
- srcBegin – индекс первого символа в строке для копирования;
- srcEnd – индекс последнего символа в строке для копирования;
- dst – массива назначения;
- dstBegin – начальное смещение в массиве назначения.
Возвращаемое значение
Пример
import java.io.*; public class Test < public static void main(String args[]) < String Str1 = new String("Добро пожаловать на ProgLang.su"); char[] Str2 = new char[7]; try < Str1.getChars(2, 9, Str2, 0); System.out.print("Скопированное значение: " ); System.out.println(Str2); >catch (Exception ex) < System.out.println("Возникает исключение. "); >> >
Получим следующий результат:
Скопированное значение: бро пож
Оглавление
- 1. Java – Самоучитель для начинающих
- 2. Java – Обзор языка
- 3. Java – Установка и настройка
- 4. Java – Синтаксис
- 5. Java – Классы и объекты
- 6. Java – Конструкторы
- 7. Java – Типы данных и литералы
- 8. Java – Типы переменных
- 9. Java – Модификаторы
- 10. Java – Операторы
- 11. Java – Циклы и операторы цикла
- 11.1. Java – Цикл while
- 11.2. Java – Цикл for
- 11.3. Java – Улучшенный цикл for
- 11.4. Java – Цикл do..while
- 11.5. Java – Оператор break
- 11.6. Java – Оператор continue
- 12. Java – Операторы принятия решений
- 12.1. Java – Оператор if
- 12.2. Java – Оператор if..else
- 12.3. Java – Вложенный оператор if
- 12.4. Java – Оператор switch..case
- 12.5. Java – Условный оператор (? 🙂
- 13. Java – Числа
- 13.1. Java – Методы byteValue(), shortValue(), intValue(), longValue(), floatValue(), doubleValue()
- 13.2. Java – Метод compareTo()
- 13.3. Java – Метод equals()
- 13.4. Java – Метод valueOf()
- 13.5. Java – Метод toString()
- 13.6. Java – Метод parseInt()
- 13.7. Java – Метод Math.abs()
- 13.8. Java – Метод Math.ceil()
- 13.9. Java – Метод Math.floor()
- 13.10. Java – Метод Math.rint()
- 13.11. Java – Метод Math.round()
- 13.12. Java – Метод Math.min()
- 13.13. Java – Метод Math.max()
- 13.14. Java – Метод Math.exp()
- 13.15. Java – Метод Math.log()
- 13.16. Java – Метод Math.pow()
- 13.17. Java – Метод Math.sqrt()
- 13.18. Java – Метод Math.sin()
- 13.19. Java – Метод Math.cos()
- 13.20. Java – Метод Math.tan()
- 13.21. Java – Метод Math.asin()
- 13.22. Java – Метод Math.acos()
- 13.23. Java – Метод Math.atan()
- 13.24. Java – Метод Math.atan2()
- 13.25. Java – Метод Math.toDegrees()
- 13.26. Java – Метод Math.toRadians()
- 13.27. Java – Метод Math.random()
- 14. Java – Символы
- 14.1. Java – Метод Character.isLetter()
- 14.2. Java – Метод Character.isDigit()
- 14.3. Java – Метод Character.isWhitespace()
- 14.4. Java – Метод Character.isUpperCase()
- 14.5. Java – Метод Character.isLowerCase()
- 14.6. Java – Метод Character.toUpperCase()
- 14.7. Java – Метод Character.toLowerCase()
- 14.8. Java – Метод Character.toString()
- 15. Java – Строки
- 15.1. Java – Метод charAt()
- 15.2. Java – Метод compareTo()
- 15.3. Java – Метод compareToIgnoreCase()
- 15.4. Java – Метод concat()
- 15.5. Java – Метод contentEquals()
- 15.6. Java – Метод copyValueOf()
- 15.7. Java – Метод endsWith()
- 15.8. Java – Метод equals()
- 15.9. Java – Метод equalsIgnoreCase()
- 15.10. Java – Метод getBytes()
- 15.11. Java – Метод getChars()
- 15.12. Java – Метод hashCode()
- 15.13. Java – Метод indexOf()
- 15.14. Java – Метод intern()
- 15.15. Java – Метод lastIndexOf()
- 15.16. Java – Метод length()
- 15.17. Java – Метод matches()
- 15.18. Java – Метод regionMatches()
- 15.19. Java – Метод replace()
- 15.20. Java – Метод replaceAll()
- 15.21. Java – Метод replaceFirst()
- 15.22. Java – Метод split()
- 15.23. Java – Метод startsWith()
- 15.24. Java – Метод subSequence()
- 15.25. Java – Метод substring()
- 15.26. Java – Метод toCharArray()
- 15.27. Java – Метод toLowerCase()
- 15.28. Java – Метод toString()
- 15.29. Java – Метод toUpperCase()
- 15.30. Java – Метод trim()
- 15.31. Java – Метод valueOf()
- 15.32. Java – Классы StringBuilder и StringBuffer
- 15.32.1. Java – Метод append()
- 15.32.2. Java – Метод reverse()
- 15.32.3. Java – Метод delete()
- 15.32.4. Java – Метод insert()
- 15.32.5. Java – Метод replace()
- 16. Java – Массивы
- 17. Java – Дата и время
- 18. Java – Регулярные выражения
- 19. Java – Методы
- 20. Java – Потоки ввода/вывода, файлы и каталоги
- 20.1. Java – Класс ByteArrayInputStream
- 20.2. Java – Класс DataInputStream
- 20.3. Java – Класс ByteArrayOutputStream
- 20.4. Java – Класс DataOutputStream
- 20.5. Java – Класс File
- 20.6. Java – Класс FileReader
- 20.7. Java – Класс FileWriter
- 21. Java – Исключения
- 21.1. Java – Встроенные исключения
- 22. Java – Вложенные и внутренние классы
- 23. Java – Наследование
- 24. Java – Переопределение
- 25. Java – Полиморфизм
- 26. Java – Абстракция
- 27. Java – Инкапсуляция
- 28. Java – Интерфейсы
- 29. Java – Пакеты
- 30. Java – Структуры данных
- 30.1. Java – Интерфейс Enumeration
- 30.2. Java – Класс BitSet
- 30.3. Java – Класс Vector
- 30.4. Java – Класс Stack
- 30.5. Java – Класс Dictionary
- 30.6. Java – Класс Hashtable
- 30.7. Java – Класс Properties
- 31. Java – Коллекции
- 31.1. Java – Интерфейс Collection
- 31.2. Java – Интерфейс List
- 31.3. Java – Интерфейс Set
- 31.4. Java – Интерфейс SortedSet
- 31.5. Java – Интерфейс Map
- 31.6. Java – Интерфейс Map.Entry
- 31.7. Java – Интерфейс SortedMap
- 31.8. Java – Класс LinkedList
- 31.9. Java – Класс ArrayList
- 31.10. Java – Класс HashSet
- 31.11. Java – Класс LinkedHashSet
- 31.12. Java – Класс TreeSet
- 31.13. Java – Класс HashMap
- 31.14. Java – Класс TreeMap
- 31.15. Java – Класс WeakHashMap
- 31.16. Java – Класс LinkedHashMap
- 31.17. Java – Класс IdentityHashMap
- 31.18. Java – Алгоритмы Collection
- 31.19. Java – Iterator и ListIterator
- 31.20. Java – Comparator
- 32. Java – Дженерики
- 33. Java – Сериализация
- 34. Java – Сеть
- 34.1. Java – Обработка URL
- 35. Java – Отправка Email
- 36. Java – Многопоточность
- 36.1. Java – Синхронизация потоков
- 36.2. Java – Межпоточная связь
- 36.3. Java – Взаимная блокировка потоков
- 36.4. Java – Управление потоками
- 37. Java – Основы работы с апплетами
- 38. Java – Javadoc
Java — String getChars() Method
This method copies characters from this string into the destination character array.
Syntax
Here is the syntax of this method −
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Parameters
Here is the detail of parameters −
- srcBegin − index of the first character in the string to copy.
- srcEnd − index after the last character in the string to copy.
- dst − the destination array.
- dstBegin − the start offset in the destination array.
Return Value
Example
import java.io.*; public class Test < public static void main(String args[]) < String Str1 = new String("Welcome to Tutorialspoint.com"); char[] Str2 = new char[7]; try < Str1.getChars(2, 9, Str2, 0); System.out.print("Copied Value = " ); System.out.println(Str2 ); >catch ( Exception ex) < System.out.println("Raised exception. "); >> >
This will produce the following result −
Output
Annual Membership
Enjoy unlimited access on 5500+ Hand Picked Quality Video Courses
Training for a Team
Affordable solution to train a team and make them project ready.
- About us
- Refund Policy
- Terms of use
- Privacy Policy
- FAQ’s
- Contact
Copyright © Tutorials Point (India) Private Limited. All Rights Reserved.
We make use of First and third party cookies to improve our user experience. By using this website, you agree with our Cookies Policy. Agree Learn more
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 literala 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 valuein 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 symmetricit 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:
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);