输入一串字符串,比如
asd dsad asd qwewq
asd sdd sad sad as
qwe wertwer wetwt
如何才能在每个空格的前后添加一个数字,asd【1】 【1】dsad【1】 【1】asd【1】 【1】qwewq
第二排数字就变为2:asd【2】 【2】sdd【2】 【2】sad【2】 【2】sad【2】 【2】as
第3排数字就变为3:qwe【3】 【3】wertwer【3】 【3】wetwt
String a= "asd dsad asd qwewq";
int num = 1;
for(int row=1;row<=3;row++) {
String k = a.replaceAll(" ", "【"+row + "】 【"+row + "】");
System.out.println(k);
num++;
}
回答楼主问楼上的问题,用scanner的nextLine就行
Scanner scan = new Scanner(System.in);
for(int row=1;row<=3;row++) {
System.out.println(scan.nextLine().replaceAll(" ", "【"+row + "】 【"+row + "】"));
}
楼主你这问题说的不清楚,你是需要好几行的字符串来判断它是第几行还是需要输入一行判断一行。
import java.util.Scanner;
public class E{
public static void main(String args[]){
Scanner reader=new Scanner(System.in);
String your=null;
System.out.println("输入字符串:");
your = reader.next();
for(int row=1;row<=3;row++) {
String A = your.replaceAll(" ", "【"+row + "】 【"+row + "】");
System.out.println(A);
}
}
}
可以试试把字母放进数组里,然后输出的时候每输出一组字母就输出一个数字
用split分隔,条件位空格,获取分隔之后的数字长都,这样,可以知道添加多少数字,之后拼起来就可以了,我好像昨天回答过了,为什么没有刷出来,好坑
public static void main(String args[]) {
String s = "asd dsad asd qwewq \n" +
"asd sdd sad sad as \n" +
"qwe wertwer wetwt";
int i = 1;
for (String str : s.split("\n")) {
str = str.replaceAll(" ", "【" + i + "】 【" + i + "】");
i++;
System.err.println(str);
}
}
输出:
asd【1】 【1】dsad【1】 【1】asd【1】 【1】qwewq【1】 【1】
asd【2】 【2】sdd【2】 【2】sad【2】 【2】sad【2】 【2】as【2】 【2】
qwe【3】 【3】wertwer【3】 【3】wetwt