package 获取字符串信息;
public class 获取字符串长度 {
public static void main(String[] args)
{
char[] a=new char[10];
String str=new String(a);
System.out.println(str.length());//获取字符串长度
}
}
package 获取字符串信息;
public class 最后出现的索引位置 {
public static void main(String[] args)
{
String str="To find a way back home";
System.out.println(str.lastIndexOf("a"));//字符串中最后一个该字符的位置的索引
System.out.println(str.lastIndexOf('1'));//如没有该字符则返回-1
}
}
package 获取字符串信息;
public class 首次出现的索引位置 {
public static void main(String[] args)
{
String str="I have a pen";
System.out.println(str.indexOf('a'));//字符串中首此出现该字符的索引位置
System.out.println(str.indexOf('1'));//没有该字符就返回-1
}
}
package 获取字符串信息;
import java.util.Scanner;
public class 获取指定索引位置的字符 {
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String str="Who am i ?";
System.out.println(str.charAt(2));//获取字符串指定位置的字符
//charAt()还可以和很多方法一起使用,通常用来获取字符
char a;
a=sc.nextLine().charAt(0);//输入字符串中的指定的字符
System.out.println(a);
}
}
![复制代码]()
package 获取字符串信息;
public class 获取字符串长度 {
public static void main(String[] args)
{
char[] a=new char[10];
String str=new String(a);
System.out.println(str.length());//获取字符串长度
}
}
package 获取字符串信息;
public class 最后出现的索引位置 {
public static void main(String[] args)
{
String str="To find a way back home";
System.out.println(str.lastIndexOf("a"));//字符串中最后一个该字符的位置的索引
System.out.println(str.lastIndexOf('1'));//如没有该字符则返回-1
}
}
package 获取字符串信息;
public class 首次出现的索引位置 {
public static void main(String[] args)
{
String str="I have a pen";
System.out.println(str.indexOf('a'));//字符串中首此出现该字符的索引位置
System.out.println(str.indexOf('1'));//没有该字符就返回-1
}
}
package 获取字符串信息;
import java.util.Scanner;
public class 获取指定索引位置的字符 {
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String str="Who am i ?";
System.out.println(str.charAt(2));//获取字符串指定位置的字符
//charAt()还可以和很多方法一起使用,通常用来获取字符
char a;
a=sc.nextLine().charAt(0);//输入字符串中的指定的字符
System.out.println(a);
}
}
package 获取字符串信息;
import java.util.Scanner;
public class 判断某文字只出现一次 {
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String str="I know I will no more than a bystander";
System.out.println("请输入你要验证的字符:");
char a=sc.next().charAt(0);
int x=str.indexOf(a);
int y=str.lastIndexOf(a);
if(x==-1)
{
System.out.println("没有该字符");
}
else if(x==y)
{
System.out.println("该字符在字符串只出现了一次");
}
else if(x!=y)
{
System.out.println("该字符在字符串中出现了不止一次");
}
}
}