String Processing in Java
Submitted by pavel7_7_7 on Sunday, September 7, 2014 - 09:25.
String class is an important and useful class to process text information in Java programs. These class provides a large number of methods that can make processing of string more efficient and understandable.
The simplest way to create a string is:
- Extract character and sub-strings from string.
The numeration of the characters in the strings begins from 0 zero.For example, if you want to extract the seventh character from the string, you will do it in the following way:
In the case you need to extract a substring, you can use
- char charAtPosition7 = myString.charAt(6);
substring
method. There are two variants of thesubstring
method: The first one extracts string from the beginIndex to endIndexExample:Another way is to extract a sub-string from the beginIndex to the end of the string:Example:Now lets test these operations:The output of the program:- Initial string This is string tutorial
- char at position 7 s
- Substring from 9th char to 14th char string
- End of string tutorial
-
You can split a string using a regular expression. For this task
split
method exists. There are two variants of split method: The first returns an array of string that matches the regex: The second has a limit for the capacity of the array: For example we can extract all the words from the string that are divided by space: The output:- This
- is
- string
- tutorial
-
Another useful method is
trim
. This method removes extra space characters from the begin and end of the string: - A string can be easily converted to upper or lower case. For this task you can use the following methods:
-
Another possibility provided by String class is searching for characters and sub-string in a string. To search for the first index of a character use:
To get the last index of character:
- int indexOf(int ch)
Also, you can specify the starting position of the search by adding a parameter to these methods:- int lastIndexOf(int ch)
The same possibility exist for searching a sub-string in a string:- int indexOf(int ch, int fromIndex)
- int lastIndexOf(int ch, int fromIndex)
All of these methods returns the index of the found character or sub-string or -1 if the character or sub-string doesn't occur. Also, you can check, if a string contains a specified char sequence:You can use any string as the parameter to this function because CharSequence is the interface of the String class.- boolean contains(CharSequence s)
-
Once a string is created, it can't be modified. So, if you need to edit a string,you will have to create a new string and use the following methods to modify the original string.
Replace old char with new char:
Replace target sub-string with new sub-string:Replace all sub-string corresponding to the regular expression: There is the modification of this method that replaces only the first occurrence of the sub-string:
Add new comment
- 280 views