【问题标题】:Find a specific char element in an Array在 Array 中查找特定的 char 元素
【发布时间】:2018-08-10 17:43:23
【问题描述】:

我试图在Array 中找到第一个空格,以便预测单词的长度,同时计算空格前char 元素的数量。我总是陷入无限循环。

请帮助我。这是我的代码:

int counter=0;                      
int i=0;

while(counter==0) {
    if (field[i]==' ') {
        counter++;
    }
    else {
        if (i==field.length-1) {
            counter++;
        }
        else {
            i++;
        }
    }
}

【问题讨论】:

  • 供参考:for (i=0; i<field.length && field[i]!=' '; ++i);

标签: java arrays char


【解决方案1】:

为什么要使用 WHILE 函数?我认为你可以这样做:

int iCharecters = 0;
for(int i = 0 ; i< word.length;i++) {
    if ( word[i] == " " ) {
        break;
    } else {
        iCharecters ++;
    }
}

【讨论】:

    【解决方案2】:

    如果你必须在数组中找到第一个空格字符,你可以使用流 API:

    Boolean spacePresent = Arrays.stream(chars)
                                 .anyMatch(it -> it == ' ')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-12
      • 2020-08-25
      • 2021-01-14
      • 2023-03-23
      • 2014-12-31
      • 1970-01-01
      • 2010-12-15
      相关资源
      最近更新 更多