编写JAVA程序:从键盘上输入字符串和子字符串开始位置与长度,截取该字符串的子串并输出

请各位大侠帮帮忙了
2024-11-29 08:49:01
推荐回答(2个)
回答1:

import java.util.*;
public class App5_8
{
public static void main(String []args)
{
System.out.println("请输入一个字符串:");
String str = new Scanner(System.in).nextLine();
System.out.println("请输入子串开始位置:");
int str1 = new Scanner(System.in).nextInt();
System.out.println("请输入子串的长度:");
int str2 = new Scanner(System.in).nextInt();
System.out.println(str.substring(str1,str1+str2));
}
}

回答2:

public class Substring {
public static void main(String[] args) throws Exception{
System.out.print("请输入一个字符串 ->:");
String str=readLine();
System.out.println("请输入子字符串的起始位置 ->:");
int start=Integer.parseInt(readLine());
System.out.println("请输入子字符串的长度 ->:");
int len=Integer.parseInt(readLine());
System.out.println("子字符串: "+str.substring(start,start+len));
}
private static String readLine()throws Exception{
byte[] buff=new byte[1024];
int read=System.in.read(buff);
return new String(buff,0,read).trim();
}
}