如何从数组对象中删除£符号并将其保存?

时间:2019-03-11 15:48:51

标签: java regex

我正在为大学项目编写一个基本的聊天机器人。我认为用户必须通过输入金额来设置预算。目前,该程序可以在用户的​​消息中搜索号码并正确保存。但是,如果在其前面加上英镑符号,则由于消息中带有英镑符号,因此无法另存为整数。

这是我的代码:

//Scan the user message for a budget amount and save it.
    for (int budgetcount = 0; budgetcount < words.length; budgetcount++) 
    {
        if (words[budgetcount].matches(".*\\d+.*"))
        {
            if (words[budgetcount].matches("\\u00A3."))
            {
                words[budgetcount].replace("\u00A3", "");
                System.out.println("Tried to replace a pound sign");
                ResponsesDAO.budget = Integer.parseInt(words[budgetcount]);
            }
            else
            {
                System.out.println("Can't find a pound sign here.");
            }
        }

我以前尝试过.contains(),以及其他指示它是我想要删除的英镑符号的方法,但是我仍然得到“在这里找不到英镑符号”的信息。打印出来。

如果有人可以提供建议或更正我的代码,我将不胜感激。

谢谢!

2 个答案:

答案 0 :(得分:3)

JAVA中的

Strings是不可变的。您正在替换,但永远不要将结果分配回words[budgetcount]

更改代码中的以下行,

words[budgetcount] = words[budgetcount].replace("\u00A3", "");

这是另一种方法,使用Character.isDigit(...)来识别数字并编织一个仅数字字符串,该字符串以后可以解析为整数,

代码段:

private String removePoundSign(final String input) {
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < input.length(); i++) {
        char ch = input.charAt(i);
        if (Character.isDigit(ch)) {
            builder.append(ch);
        }
    }
    return builder.toString();
}

输入:

System.out.println(removePoundSign("£12345"));

输出:

12345

答案 1 :(得分:1)

您还可以使用String.replaceAll方法。

代码段:

public class TestClass {

    public static void main(String[] args){

        //Code to remove non-digit number
        String budgetCount = "£34556734";
        String number=budgetCount.replaceAll("[\\D]", "");
        System.out.println(number);

        //Code to remove any specific characters
        String special = "$4351&2.";
        String result = special.replaceAll("[$+.^&]",""); // regex pattern
        System.out.println(result);

    }
}

输出:

34556734
43512
相关问题