我想插入空格,如所需的输出
所示 input string :abc
必需的输出:
abcabc
ab--bc
a----c
但我的是:
abcabc
abbc
ac
public static void triangle(String s){
int length = s.length();
for(int i=0;i<2*length;i++){
System.out.println();
for(int j=0;j<length-i;j++){
System.out.print(" "+s.charAt(j));
}
for(int k=i;k<length;k++){
System.out.print(" "+s.charAt(k));
}
}
}
答案 0 :(得分:1)
public static void triangle(String s){
int length = s.length();
for(int i=0;i<length;i++){
System.out.println();
int j=0;
while(j<length-i){
System.out.print(s.charAt(j));
j++;
}
while(j<length){
System.out.print(" ");
j++;
}
int k=0;
while(k<i){
System.out.print(" ");
k++;
}
while(k<length){
System.out.print(s.charAt(k));
k++;
}
}}
将它放在while循环中。
答案 1 :(得分:1)
或只是for循环:)
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < s.length()-i; j++) {
System.out.print(s.charAt(j));
}
for (int j = s.length()-i; j < s.length(); j++) {
System.out.print(" ");
}
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
for (int j = i; j < s.length(); j++) {
System.out.print(s.charAt(j));
}
System.out.println("");
}