In this tutorial, we will continue our study of strings in Java. The basics of working with strings can be found in the lesson "Strings in Java". A class
String
in Java has a set of methods for manipulating the contents of a string. Find characters, substrings, change case and other tasks.
Getting characters and substrings
You can get a character at a specific position in a string by calling thecharAt()
. The index of the first character in the string is 0, the last is length()
-1. The following code returns the 9 character of a string.
String anotherPalindrome = "Niagara. O roar again!";
char aChar = anotherPalindrome.charAt(9);
The numbering of characters starts from 0, so the 9th character in the string is "O". If you need to get not just one character, but part of a string, you can use the substring
. The method substring
has two options: The following code will return a substring of the string starting at character 11 but not including character 15, resulting in the word "roar"
String anotherPalindrome = "Niagara. O roar again!";
String roar = anotherPalindrome.substring(11, 15);
Other Methods for Manipulating Strings
The table shows some methods for working with strings and their description.Finding characters and substrings
Let's look at a few more methods for searching for characters and substrings. The classString
contains methods that return the position of a character or substring in a string: indexOf()
and lastIndexOf()
. Methods indexOf()
search from the beginning of the string, lastIndexOf()
- from the end. If these methods do not find a match, they return -1. The class also String
contains a method contains
that returns true if the given sequence of characters is contained in the string. Use this method if you need to find out about the existence of a substring in a string, and its position is not important. The following table describes the indexOf()
and methods lastIndexOf()
. CharSequence
is an interface that the class implements String
, so you can pass strings to the contains()
.
Changing lines. Replacing characters and substrings
The classString
has several methods for inserting characters and substrings into a string. The table describes methods for replacing found characters and substrings.
Example
The following classFilename
shows an example of using the lastIndexOf()
and methods substring()
to use different parts of a string with a file name. Now consider a program that uses the class Filename
: The program will output: The method extension
uses the method lastIndexOf
to determine the last occurrence of " .
". The method substring
uses this value to find the file extension. Link to the source: Manipulating strings, functions for working with strings in Java Managing strings, functions for working with strings in Java. Part 2
GO TO FULL VERSION