问题描述:在字符串中寻找特定字符
1、第1次出现位置
实现函数原型: int indexOf(char c)
Java代码:
import java.io.*;
public class Way_1
{
public static void main(String args[])
{
String str = "Geeks for Geeks is a computer science portal";
System.out.println(str.length());
int firstIndex = str.indexOf('s');
System.out.println("First occurrence of char 's' is found at: " + firstIndex);
int firstIn = str.indexOf('z');
System.out.println("First occurrence of char 'z' is found at: " + firstIn);
}
}
样例字符串: Geeks for Geeks is a computer science portal
样例输出:
2、最后一次出现位置
实现函数原型: public int lastIndexOf(char c)
Java代码:
import java.io.*;
public class Way_2
{
public static void main(String args[])
{
String str = "Geeks for Geeks is a computer science portal";
System.out.println(str.length());
int lastIndex = str.lastIndexOf('s');
System.out.println("Last occurrence of char 's' is found at: " + lastIndex);
int lastIn = str.lastIndexOf('z');
System.out.println("Last occurrence of char 'z' is found at: " + lastIn);
}
}
样例字符串: Geeks for Geeks is a computer science portal
样例输出:
3、指定位置后的首次出现
实现函数原型: public int IndexOf(char c, int indexFrom)
说明: 除-1外,该函数的返回值必然大于或等于其第2个参数indexFrom。
Java代码:
import java.io.*;
public class String_Search
{
public static void main(String [] args)
{
String str = "Geeks For Geeks is a computer science portal";
System.out.println(str.length());
int first_in = str.indexOf('s', 10);
System.out.println("First occurrence of char 's' after index 10: " + first_in);
int first_not_in = str.indexOf('z', 10);
System.out.println("First occurrence of char 'z' after index 10: " + first_not_in);
}
}
样例字符串: Geeks For Geeks is a computer science portal
样例输出:
4、指定位置前的末次出现
实现函数原型: public int lastIndexOf(char c, int fromIndex)
说明: 除-1外,该函数的返回值必然小于或等于其第2个参数fromIndex。
Java代码:
import java.io.*;
public class String_Search_2
{
public static void main(String [] args)
{
String str = "Geeks For Geeks is a computer science portal";
System.out.println(str.length());
int lastIndex = str.lastIndexOf('s', 20);
System.out.println("Last occurrence of char 's' before index 20: " + lastIndex);
int last_not_in = str.lastIndexOf('z', 20);
System.out.println("Last occurrence of char 'z' before index 20: " + last_not_in);
}
}
样例字符串: Geeks For Geeks is a computer science portal
样例输出:
5、指定位置的字符
实现函数原型: char charAt(int indexNumber)
说明: 若指定的下标indexNumber超出字符串长度范围,则抛出StringIndexOutOfBounds异常。
Java代码:
import java.io.*;
public class Character_At
{
public static void main(String [] args)
{
String str = "Geeks For Geeks is a computer science portal";
System.out.println(str.length());
int char_at = str.charAt(20);
System.out.println("Character at location 20: " + char_at);
int char_not_at = str.charAt(60);
}
}
样例字符串: Geeks For Geeks is a computer science portal
样例输出: