【问题标题】:I need to get two numbers of a string like like this "5+7", but when im using .split(\\+) only get the first, how can i get both? [closed]我需要像这样“5 + 7”这样的字符串的两个数字,但是当我使用 .split(\\+) 时只得到第一个,我怎样才能得到两个? [关闭]
【发布时间】:2014-11-02 02:59:28
【问题描述】:
String x = "5+7";
String []n = x.split("\\+");

System.out.println(n[0]); //  =5
System.out.println(n[1]); //  =\

【问题讨论】:

  • 您确定您的代码不起作用吗?
  • 它确实有效.. ideone.com/xnGnj1
  • @Droidman 我认为由于 cmets 损坏,代码不会在当前状态下工作。

标签: java string split


【解决方案1】:

您的代码应该可以正常工作,但我会尝试使其更健壮:

  String test = "5 + 7";
  String[] tokens = test.split("\\s*\\+\\s*");

  for (String token : tokens) {
     System.out.println(token);
  }

\\s* 将允许数字和 + 字符之间可能存在空白。

【讨论】:

    【解决方案2】:

    使用

    x.split("[+]");
    

    这将正确拆分它。

    【讨论】:

    • 这比原发帖人的代码好多少?
    • 当我使用 x.split("[+]"); 时出现此错误5---这是 n[0] 但在 n[1] 中显示此错误 线程“AWT-EventQueue-0”中的异常 java.lang.ArrayIndexOutOfBoundsException: 1
    猜你喜欢
    • 2022-10-13
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多