【问题标题】:Dividing a String in multiple parts将字符串分成多个部分
【发布时间】:2014-01-26 19:14:59
【问题描述】:

我正在做一些学校作业,但偶然发现了一个问题。

我必须将相同的字符串分成 3 部分才能得到如下所示的输出:XXX-XXXXXXX-XX

我考虑过使用子字符串,这样我就可以轻松地拆分字符串,但是当我在我的 String.format 中多次使用它时,它总是返回错误。

这就是我的班级的样子

public class BankAccount {
private String account;

public BankAccount(String account) {
    this.account = account;
}

@Override
public String toString() {
    return String.format("%s - %s - %s", account.substring(0, 3), account.substring(3 - 10), account.substring(10 - 12));
}

}

任何帮助将不胜感激,在此先感谢!

【问题讨论】:

  • account.substring(3 - 10),不好。你在找substring(int beginIndex, int endIndex) 吗?
  • 是的,这不是很好吗?
  • 你的返回字符串是account.substring(3 - 10), and (10 - 12));应该是account.substring(3, 10), and (10, 12));
  • 您可能需要阅读doc:"IndexOutOfBoundsException - 如果 beginIndex 为负数或大于此 String 对象的长度。".
  • 呃,该死的我没有注意到我使用了“-”符号。而且我的IDE没有提到任何错误,那么使用的“-”标签是什么?

标签: java string split substring


【解决方案1】:

account.substring(3 - 10)

应该是

account.substring(3, 10)

account.substring(10 - 12) 也是如此

【讨论】:

  • 看起来像是复制/粘贴错误;)
猜你喜欢
  • 2016-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-27
  • 1970-01-01
相关资源
最近更新 更多