我正在尝试更改创建一个没有空格的Str的新字符数组中的信息。但是,我不能成功地做sp
我不知道为什么输出说:
Haveaniceday
祝你有愉快的一天
而不是:
Haveaniceday
Haveaniceday
import java.util.*;
class DelExtraSpace
{
public static void main(String args[])
{
char c[],s[];
String str;
Scanner scn = new Scanner(System.in);
str = "Have a nice day";
c = str.toCharArray();
s = new char [c.length];
for(int i = 0; i < c.length; i++)
{
if(!Character.isSpaceChar(c[i]))
{
System.out.print(c[i]);
s[i] = c[i]; // I want the value of c[i] to be assigned to s[i] only when c[i] is not a whitespace
}
}
System.out.println();
for(int j = 0; j < s.length; j++)
System.out.print(s[j]);
}
}
答案 0 :(得分:1)
我想你想知道为什么s
没有改变。
在这种情况下,试试这个:
public static void main(String args[]) {
char c[], s[];
String str;
Scanner scn = new Scanner(System.in);
str = "Have a nice day";
c = str.toCharArray();
s = new char[c.length];
int ii = 0; // ADDED
for (int i = 0; i < c.length; i++) {
if (!Character.isSpaceChar(c[i])) {
System.out.print(c[i]);
s[ii] = c[i]; // CHANGED
ii++; // ADDED
}
}
System.out.println();
for (int j = 0; j < s.length; j++)
System.out.print(s[j]);
}
我为修改后的/添加的行添加了3条评论。
现在输出应为:
Haveaniceday
Haveaniceday
简短说明
显然,s
会比c
短(因为它不包含这些空格)。
这就是您需要新的控件(ii
)而不是i
的原因。
ii
取0到11之间的值i
取0到17之间的值ii -> i 0 -> 0 1 -> 1 2 -> 2 3 -> 3 // 4 and 5 are indexes for spaces => they are ignored 4 -> 6 // 7 is index for space => it is ignored 5 -> 8 6 -> 9 7 -> 10 8 -> 11 // 12, 13 and 14 are indexes for spaces => they are ignored 9 -> 15 10 -> 16 11 -> 17
例如:当忽略4和5时,ii
没有增加,因为我们在最终数组中不需要“间隙”,只需要不是空格的值。