输出这个字符数组java程序

时间:2014-08-24 23:09:34

标签: java arrays string

我正在尝试更改创建一个没有空格的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]);
    }
}

1 个答案:

答案 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没有增加,因为我们在最终数组中不需要“间隙”,只需要不是空格的值。

相关问题