Substrings
Lesson 7 of 16 in Coddy's Strings and Arrays in Java course.
Let's learn some more string methods related to substrings!
To get a substring (portion of a string) of some string in Java use the method substring() with the start and end index(s),
String word = "howareyou";
String sub = word.substring(3, 6);In the above example, sub will hold the string "are" because the 3rd index is the character 'a' and the 6th index is the character 'y' but the end index is excluded.
Remember! indexes are starting from 0 (like in
charAt()method)
Another important method is indexOf() which returns the position of the first found occurrence of a specified character(s) in a string,
String sentence = "how$are$you";
int i = word.indexOf("$"); // Returns 3
String sub = sentence.substring(0, i);In the above example, we find the position of the first occurrence of "$" in sentence, in the end sub will hold "how".
Note! If you use
substring()with just one argument, for examples.substring(2), it will return the substring from the 2nd index to the end!
The last method we will learn here is contains() which checks whether a string contains a sequence of characters,
String sentence = "how$are$you";
boolean res1 = sentence.contains("$"); // Returns false
boolean res2 = sentence.contains('); // Returns true
boolean res2 = sentence.contains("are"); // Returns trueThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyWrite a function named getFirstPart that takes a string (s) as an argument and returns its first part.
String's first part is the substring before the first occurrence of ",", if there is no "," in s the first part is "NONE"
Try it yourself
class GetFirstPart {
public static String getFirstPart(String s) {
// Write code here
}
}