繁体   English   中英

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

[英]How can I remove a £ symbol from an array object and save it?

我正在为大学项目编写一个基本的聊天机器人。 我已经到了用户必须通过输入金额来设置预算的地步。 目前,该程序能够搜索用户消息中的数字并正确保存。 但是,当一个 £ 符号作为前缀时,由于消息中有井号,它无法保存为整数。

这是我的代码:

//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() 和其他方法来表明它是我想删除的英镑符号,但我仍然得到“在这里找不到英镑符号”。 打印。

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

提前致谢!

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

您还可以使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM