【问题标题】:Issues with white space while converting string to long将字符串转换为长字符串时出现空格问题
【发布时间】:2016-04-20 15:40:22
【问题描述】:

我试图从一个字符串中分离出 3 个数字并将它们打印到字符串中。我需要我的程序使用空格作为分隔符来表明我在这个数字的末尾。然后我需要开始下一个数字作为循环的新迭代。但是,我认为由于不了解空格无法转换而崩溃。

对此我能做些什么?

String cipherTxt = "45963254 45231582 896433482 ";
for(int i=0; i<cipherTxt.length(); i++){
     String numberAsString = cipherTxt.substring(i,i+9);
     long number = Long.parseLong(numberAsString);
     System.out.println("The number is: " + number);
}

【问题讨论】:

  • 为什么不直接拆分字符串呢? String[] numbers = text.split(" ");
  • 如果空格困扰您,请使用Stringtrim() 方法。
  • 我必须保留空格。我对拆分不熟悉……那到底是在做什么?

标签: java string for-loop long-integer


【解决方案1】:

尝试使用更简单的Scanner 类,如

String txt = "45963254 45231582 896433482 ";
Scanner scanner = new Scanner(txt);
while(scanner.hasNext())
    System.out.println(scanner.nextLong());

或者,如果你愿意,也可以String.split()

String txt = "45963254 45231582 896433482 ";
String[] tokens = txt.split(" ");
for(String temp:tokens)
    System.out.println(Long.parseLong(temp));

【讨论】:

  • 有人能解释一下这些 for 循环吗?我根本不懂这个符号。
  • 只能指点你hereand here
【解决方案2】:

你为什么不能尝试这样的事情:

String cipherTxt = "45963254 45231582 896433482 ";
String[] splitted = cipherTxt.split("\\s+");

for(String s : splitted){
     long number = Long.parseLong(s);
     System.out.println("The number is: " + number);
}

【讨论】:

  • 您能向我解释一下您的 for 循环,因为我会这么写吗?你能解释一下分裂吗? @dambros
  • 您应该在拆分之前trim(),否则像双空格之类的东西会导致数组上的条目无效。
【解决方案3】:

使用正则表达式\d+ 查找数字。遍历所有给定的数字并将它们保存到List,以便之后您可以再次使用存储的变量。

String txt = "45963254 45231582 896433482 ";

List<Long> list = new ArrayList<>();
Matcher m = Pattern.compile("\\d+").matcher(txt);
while (m.find()) {
   long l = Long.parseLong(m.group());
   list.add(l);
   System.out.println(l);
}

如果您希望将数组作为输出,请在循环下添加:

Long[] numbers = list.toArray(new Long[list.size()]);

【讨论】:

    【解决方案4】:

    做:

    String cipherTxt = "45963254 45231582 896433482 ";
    String[] splitted = cipherTxt.split("\\s+");
    
    for(String s : splitted){
         long number = Long.parseLong(s);
         System.out.println(number);
    }
    

    这个 for 循环遍历数组中的每个字符串拆分 然后它使文本变长。 你也可以这样写:

    for(int i = 0; i < splitted.length;i++){
         long number = Long.parseLong(splitted[i]);
         System.out.println(number);
    }
    

    希望我能帮上忙!

    编辑: 当然,如果您有任何问题,请提出!

    【讨论】:

      猜你喜欢
      • 2020-03-17
      • 2021-12-05
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-19
      • 2014-06-15
      相关资源
      最近更新 更多