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("该字符在字符串中出现了不止一次");
}
}
}

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)