Substring in JavaA part of String is called substring. In other words, substring is a subset of another String. Java String class provides the built-in substring() method that extract a substring from the given string by using the index values passed as an argument. In case of substring() method startIndex is inclusive and endIndex is exclusive. Suppose the string is "computer", then the substring will be com, compu, ter, etc. Note: Index starts from 0.You can get substring from the given String object by one of the two methods:
In case of String:
Let's understand the startIndex and endIndex by the code given below. In the above substring, 0 points the first letter and 2 points the second letter i.e., e (because end index is exclusive). Example of Java substring() methodTestSubstring.java Output: Original String: SachinTendulkar Substring starting from index 6: Tendulkar Substring starting from index 0 to 6: Sachin The above Java programs, demonstrates variants of the substring() method of String class. The startindex is inclusive and endindex is exclusive. Using String.split() method:The split() method of String class can be used to extract a substring from a sentence. It accepts arguments in the form of a regular expression. TestSubstring2.java Output: [Hello, My name is Sachin] In the above program, we have used the split() method. It accepts an argument \\. that checks a in the sentence and splits the string into another string. It is stored in an array of String objects sentences. Next TopicMethods Of String class |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India