【问题标题】:Find certain numbers in a String and add them in separate ints在字符串中查找某些数字并将它们添加到单独的整数中
【发布时间】:2022-01-19 23:11:43
【问题描述】:

我需要一种方法来从字符串中获取特定的“随机”数字,并将它们分别放入单独的 int 变量中。 例如,这个字符串不能/不应该改变: String date = "59598 22-01-19 22:46:32 00 0 0 66.2 UTC(NIST) * ";

我需要将这三个数字放在单独的整数“22-01-19”中。 因此,一个 int 称为“day”,它保存数字 19,另一个 int 称为“month”,它保存数字 1,另一个 int 称为“year”,它保存数字 22。

这就是它的样子:

String date = "59598 22-01-19 22:46:32 00 0 0  66.2 UTC(NIST) * ";
int day = 0;
int month = 0;
int year = 0;

//(method for finding these numbers and putting them into the separate int variables)

System.out.println(year+" "+month+" "+day);

提前谢谢你!

注意:我没有找到一个解释得足够好让我理解的解决方案,如果这个问题已经存在重复,我深表歉意。

【问题讨论】:

    标签: java string


    【解决方案1】:

    您可以将date 拆分两次以获得日期列表

    String date = "59598 22-01-19 22:46:32 00 0 0  66.2 UTC(NIST) * ";
    String[] splittedDate = date.split(" ")[1].split("-");
    
    int day = Integer.valueOf(splittedDate[2]);
    int month = Integer.valueOf(splittedDate[1]);
    int year = Integer.valueOf(splittedDate[0]);
    
    //(method for finding these numbers and putting them into the separate int variables)
    
    System.out.println(year+" "+month+" "+day);
    

    【讨论】:

      【解决方案2】:

      您需要从字符串中提取日期(那些特定值)。您可以使用正则表达式 (regex) 来提取它。 看看这个与您想要实现的解决方案类似的解决方案 https://stackoverflow.com/a/33924024/6099890

      【讨论】:

        【解决方案3】:

        假设日期始终是第二个令牌,您可以这样做。

        • 用空格分割字符串,并使用第二个标记
        • 定义一个格式化程序来解析分配给LocalDate 实例的日期。
        • 然后提取值
        • 您可以使用这些提取来重新格式化日期
        • 或者您可以使用格式化程序
        String date = "59598 22-01-19 22:46:32 00 0 0  66.2 UTC(NIST) * ";
        
        String[] tokens = date.split("\\s+", 3);
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(("dd-MM-y"));
        LocalDate ld = LocalDate.parse(tokens[1], dtf);
        
        int day = ld.getDayOfMonth();
        int year = ld.getYear();
        int month = ld.getMonthValue();
        
        System.out.printf("%02d-%02d-%02d%n", day, month, year);
        System.out.println(ld.format(dtf));
        

        打印

        22-01-19
        22-01-19
        

        有关更多信息,请查看java.time 包。如果您要解析或操作日期/时间对象,这是一个必须了解的类。

        【讨论】:

        • 感谢您的回复,我同意这行得通,但是对于我想要完成的工作来说,这不是很不切实际吗?我正在操作的字符串在技术上只是一个普通的字符串,那么为什么不使用 Marcos Blandim 回答的方法呢?这也是一个额外的进口。一般来说,您希望尽可能少地导入,对吗?
        • 我只是举了一个替代的例子。但我的最后一句话仍然有效,
        • 是的,这是真的。再次感谢你。 :)
        猜你喜欢
        • 1970-01-01
        • 2015-06-12
        • 2020-11-27
        • 1970-01-01
        • 1970-01-01
        • 2020-09-23
        • 2019-06-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多