需求:输入一个字符串,对字符串进行添加,删除,修改。
import java.util.Scanner;
public class StringTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入字符串:");
StringBuffer zfc =null;
String str = sc.next();
zfc = new StringBuffer(str);
System.out.println("1.添加字符:(输入字符)");
String add = sc.next();
System.out.println("请选择添加的位置:(第 个字符后)");
int a = sc.nextInt();
if(a>zfc.length()) {
System.out.println("超过字符串长度!");
}else {
System.out.println(zfc.insert(a, add));
}
System.out.println("2.删除字符:");
System.out.println("请选择删除的位置:(从字符串第 个位置到第 个位置)");
int b = sc.nextInt();
int c = sc.nextInt();
System.out.println(zfc.delete(b-1, c));
System.out.println("3.修改字符:(输入字符)");
String delete = sc.next();
System.out.println("请选择修改的位置:(从字符串第 个位置到第 个位置)");
int d = sc.nextInt();
int e = sc.nextInt();
System.out.println(zfc.replace(d-1, e, delete));
}
}