【问题标题】:Reading a line ignoring special values读取忽略特殊值的行
【发布时间】:2015-04-12 00:58:23
【问题描述】:

如何在没有 -> 的情况下从 A B -> carry sum 中提取每个字符串?所以,我只需要得到ABcarrysum。怎么办?

A B -> carry sum 作为字符串传递给方法。

public void parseContactsLine(String line)
{
    Scanner readLine = new Scanner(line);

    while(readLine.hasNext())
    {

    }
}

【问题讨论】:

标签: java


【解决方案1】:

您可以使用split() 方法拆分字符串:

public void parseContactsLine(String line)
{
    Scanner readLine = new Scanner(line);

    while(readLine.hasNext())
    {
        String[] parts = line.split("->");
        int a = Integer.parseInt(parts[0].split("\\s+")[0]); // Split string by whitespaces
        int b = Integer.parseInt(parts[0].split("\\s+")[1]);            
        int carry = Integer.parseInt(parts[1].trim().split("\\s+")[0]);
        int sum = Integer.parseInt(parts[1].trim().split("\\s+")[1]);
        // Do whatever you want with a, b, carry and sum
    }
}

【讨论】:

    【解决方案2】:

    你可以打破空格周围的字符串,并忽略 -> 你可以使用正则表达式,使用 string.split 函数,甚至迭代字符串并自己做

    【讨论】:

    • 您知道每个输入将有 5 个按来源分隔的字符串,您知道第三个是箭头。听起来你是在为一个类做这个,所以自己实现这个功能是理想的
    猜你喜欢
    • 1970-01-01
    • 2017-07-25
    • 2011-01-15
    • 1970-01-01
    • 2013-12-11
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多