我正在尝试更改创建不带空格的新 Str 字符数组的信息。但是,我无法成功执行 sp
我不知道为什么输出显示:
祝你生日快乐
祝你有美好的一天
而不是:
祝你生日快乐
祝你节日快乐
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]);
}
}
最佳答案
我想您想知道为什么 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
短(因为它不包含这些空格)。
这就是为什么您需要一个新的 contor (ii
) 而不是 i
。
ii
取值范围为 0 到 11i
取值范围为 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
不会递增,因为我们在最终数组中不需要“间隙”,只需要非空格的值。
关于java - 这个字符数组java程序的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25477134/