简体   繁体   English

if 语句中的 Java 子字符串不起作用

[英]Java Substring in if statement does not work

I'm trying to remove the last char in the string using substring method.我正在尝试使用substring方法删除字符串中的最后一个字符。 Outside the if statement works normally.在 if 语句之外正常工作。 But inside it just goes through the if statement and returns original String .但在它内部只是通过 if 语句并返回原始String

public String getElkon(int p, int zbytek) {   
    System.out.println(zbytek);

    for (int i = 0; i < p; i++) {
        vysledek += elkon[i];
        vysledek += " ";
        System.out.println(vysledek);
    }
  ***if(zbytek != 0){
        vysledek = vysledek.substring(0, vysledek.length() - 1);
        return vysledek;
    }
    else{
        return vysledek;
    }***

}

Your code would be more straightforward if you didn't have to trim the trailing space from appending your String (s).如果您不必通过附加String来修剪尾随空格,您的代码会更简单。 Also, it isn't clear why you expect zbytek to control the trim .此外,不清楚为什么您希望zbytek控制trim I think you wanted if (p != 0) (since that is your loop sentinel).我想你想要if (p != 0) (因为那是你的循环哨兵)。 I would use a StringJoiner to implement this like我会使用StringJoiner来实现这个

public String getElkon(int p, int zbytek) {
    System.out.println(zbytek);
    StringJoiner sj = new StringJoiner(" ");
    for (int i = 0; i < p; i++) {
        sj.append(elkon[i]);
    }
    return sj.toString();
}

The last character in the string is a space, since you added it last time in the for loop.字符串中的最后一个字符是一个空格,因为您上次在for循环中添加了它。

To trim the last space before if statement you could use the code要修剪if语句之前的最后一个空格,您可以使用代码

public String getElkon(int p, int zbytek) {   
    System.out.println(zbytek);

    for (int i = 0; i < p; i++) {
        vysledek += elkon[i];
        vysledek += " ";
        System.out.println(vysledek);
    }

    if (p > 0)
        vysledek = vysledek.substring(0, vysledek.length() - 1);

    if(zbytek != 0){    
       ...
    }

    return vysledek;     
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM