[英]Output of this character array java program
我正在尝试在创建没有空白的Str的新字符数组时更改信息。 但是,我做不到成功
我不知道为什么输出说:
祝你今天愉快
祝你今天愉快
代替:
祝你今天愉快
祝你今天愉快
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
短(因为它不包含那些空格)。 这就是为什么您需要一个新的控制( 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
不会增加,因为我们在最终数组中不需要“间隙”,只需要不是空格的值即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.