翻译自https://www.geeksforgeeks.org/java-string-indexof/
1 String indexOf(char c):此方法返回c字符在string中的下标【不存在则返回-1】
解释代码:
// Java code to demonstrate the working
// of String indexOf()
public class Index1 {
public static void main(String args[])
{
// Initialising String
String gfg = new String("Welcome to geeksforgeeks");
System.out.print("Found g first at position : ");
// Initial index of 'g' will print
// prints 11
System.out.println(gfg.indexOf('g'));
}
}
输出:
Found g first at position : 11
2 String indexOf(char c, int strt):此方法从下标strt处开始查找c字符在string中的下标【不存在则返回-1】
解释代码:
// Java code to demonstrate the working
// of String indexOf(char ch, int strt)
public class Index2 {
public static void main(String args[])
{
// Initialising String
String gfg = new String("Welcome to geeksforgeeks");
System.out.print("Found g after 13th index at position : ");
// 2nd index of 'g' will print
// prints 19
System.out.println(gfg.indexOf('g', 13));
}
}
输出:
Found g after 13th index at position : 19
3 String indexOf(String str):此方法返回字符串在string中的下标【不存在则返回-1】
解释代码:
// Java code to demonstrate the working
// of String indexOf(String str)
public class Index3 {
public static void main(String args[])
{
// Initialising string
String Str = new String("Welcome to geeksforgeeks");
// Initialising search string
String subst = new String("geeks");
// print the index of initial character
// of Substring
// prints 11
System.out.print("Found geeks starting at position : ");
System.out.print(Str.indexOf(subst));
}
}
输出:
Found geeks starting at position : 11
4 String indexOf(String str, int strt):此方法从下标strt处开始查找字符str在string中的下标【不存在则返回-1】
解释代码:
// Java code to demonstrate the working
// of String indexOf(String str, int strt)
public class Index4 {
public static void main(String args[])
{
// Initialising string
String Str = new String("Welcome to geeksforgeeks");
// Initialising search string
String subst = new String("geeks");
// print the index of initial character
// of Substring aftr 14th position
// prints 19
System.out.print("Found geeks(after 14th index) starting at position : ");
System.out.print(Str.indexOf(subst, 14));
}
}
输出:
Found geeks(after 14th index) starting at position : 19
5 其他相关的应用
Finding out if a given character (maybe anything upper or lower case) is a vowel or consonant.
Implementation is given below:
解释代码
class Vowels
{
// function to check if the passed
// character is a vovel
public static boolean vowel(char c)
{
return "aeiouAEIOU".indexOf(c)>=0;
}
// Driver program
public static void main(String[] args)
{
boolean isVowel = vowel('a');
// Printing the output
if(isVowel)
System.out.println("Vowel");
else
System.out.println("Consonant");
}
}
输出:
Vowel