【问题标题】:How Do I separate String from Integer and Save it如何将字符串与整数分开并保存
【发布时间】:2011-12-11 15:13:42
【问题描述】:

我想知道如何将字符串分成两部分并将其保存在两个不同的变量中。

我有:

String str = "3-abc";

并希望将其保存在两个字符串中:

String part1 = "3";
String part2 = "abc";

任何帮助将不胜感激,谢谢

【问题讨论】:

标签: java string split integer


【解决方案1】:
String[] strArray = str.split("-");
String part1=strArray[0]; 
String part2=strArray[1];

【讨论】:

    【解决方案2】:

    你可以使用拆分功能

    String[] temp;
    String delimiter = "-";
    temp = str.split(delimter);
    for(int i =0; i < temp.length ; i++)
       System.out.println(temp[i]);
    

    【讨论】:

      【解决方案3】:

      您可以使用String 类的split 方法。所以

      String[] parts = str.split("-");
      
      String part1 = parts[0];
      String part2 = parts[1];
      

      来自Java Documentation

      Splits this string around matches of the given regular expression. 
      
      
      Returns:
          the array of strings computed by splitting this string around 
          matches of the given regular expression 
      

      【讨论】:

        【解决方案4】:

        如果字符串都是一种格式,您可以使用String[] splittedStrings = str.split("-"); 之后尝试使用Integer.parseInt(splittedStrings[0]); 将您的字符串转换为整数

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-01-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-04-26
          • 2017-06-22
          相关资源
          最近更新 更多