Java Tutorial/Data Type/Extracting String Characters
Содержание
- 1 Beyond the last character of the substring
- 2 Finding the last occurrence of "a" in the String variable text: the method lastIndexOf()
- 3 Last index of
- 4 Searching for Substrings
- 5 Searching Strings for Characters
- 6 String Characters
- 7 To search forwards from a given position: startIndex
- 8 Up to the end of the string
Beyond the last character of the substring
<source lang="java">
public class MainClass{
public static void main(String[] arg){ String place = "abcedfghijk"; String segment = place.substring(7, 11); System.out.println(segment); }
}</source>
hijk
Finding the last occurrence of "a" in the String variable text: the method lastIndexOf()
<source lang="java">
public class MainClass{
public static void main(String[] arg){ String str = "abcdea"; int index = 0; index = str.lastIndexOf("a"); System.out.println(index); }
}</source>
5
Last index of
<source lang="java">
public class MainClass{
public static void main(String[] arg){ String str = "abcdeabcdef"; int index = 0; index = str.lastIndexOf("ab"); System.out.println(index); }
}</source>
5
Searching for Substrings
<source lang="java">
public class MainClass{
public static void main(String[] arg){ String str = "abcdeabcdef"; int startIndex = 3; int index = 0; index = str.indexOf("ab", startIndex); System.out.println(index); }
}</source>
5
Searching Strings for Characters
<source lang="java">
public class MainClass{
public static void main(String[] arg){ String str = "abcde"; int index = 0; index = str.indexOf("c"); System.out.println(index); }
}</source>
2
String Characters
<source lang="java">
public class StringCharacters {
public static void main(String[] args) { String text = "To be or not to be?"; int spaces = 0, vowels = 0, letters = 0; for (int i = 0; i < text.length(); i++) { char ch = Character.toLowerCase(text.charAt(i)); if (ch == "a" || ch == "e" || ch == "i" || ch == "o" || ch == "u") ++vowels; if (Character.isLetter(ch)) ++letters; if (Character.isWhitespace(ch)) ++spaces; } }
}</source>
To search forwards from a given position: startIndex
<source lang="java">
public class MainClass{
public static void main(String[] arg){ String str = "abcdea"; int startIndex = 3; int index = 0; index = str.indexOf("a", startIndex); System.out.println(index); }
}</source>
5
Up to the end of the string
<source lang="java">
public class MainClass{
public static void main(String[] arg){ String place = "abcedfghijk"; String lastWord = place.substring(5); System.out.println(lastWord); }
}</source>
fghijk