【问题标题】:How do I limit the length of a string so that if the length is more than 100 it will cause an error?如何限制字符串的长度,以便如果长度超过 100 会导致错误?
【发布时间】:2017-11-20 19:48:27
【问题描述】:

为了进一步解释我的问题,我有一个方法可以打印用户输入的字符串的长度。我现在正在尝试如果我输入一个字符串“你好”,那么输出是“05”。

如果我输入的字符串超过 100 个字符,则输出将是 '100'、'101'、'305' 等等。因此,要澄清我如何做到这一点,以便如果字符串超过 100 则不允许它并导致错误?

我关心的主要代码部分是:String.format("%02d", message.length())

目前,如果字符串长度小于 10,它会在数字前面显示 0。例如,字符串“hello”显示 05 而不是 5。

我希望我走在正确的轨道上,任何帮助都会得到帮助

谢谢

public void sendMessage(String message) throws ProtocolException
{ physicalLayer.sendFrame("<" + "E" + "-" + **String.format("%02d", message.length())** + "-" + message +
    "-" + sum%100 + ">");
}

【问题讨论】:

标签: java string string-length


【解决方案1】:

如果字符串超过 100,我该如何做到这一点,它不会被允许并导致错误?

    public void sendMessage(String message) throws ProtocolException, Exception
    { 

    // Check the length and throw an Exception if more than 100
    if (message.length()>100)
    throw new Exception("Length is more than 100");

    physicalLayer.sendFrame("<" + "E" + "-" + **String.format("%02d", message.length())** + "-" + message +
        "-" + sum%100 + ">");
    }

【讨论】:

    【解决方案2】:

    string.length(),或者如果你想取前100个字母:

    String first100 = s.substring(0, Math.min(s.length(), 100));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多