简体   繁体   中英

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

I'm coding a basic chatbot for a University project. I'm up to a point where the user must set a budget by entering an amount. At the moment, the program is able to search for a number in the user's message and save it correctly. However, when a £ sign is prefixed to it, it can't save as an integer due to having the pound sign in the message.

This is my code:

//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.");
            }
        }

I have previously tried .contains(), and other ways of indicating that it is a pound sign that I want to remove but I still get the "Can't find a pound sign here." print out.

If anybody can offer advice or correct my code I would appreciate it greatly.

Thanks in advance!

Strings in JAVA are immutable. You are replacing but never assigning back the result to words[budgetcount] .

Change the following line in your code,

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

Here is another way to do it by using Character.isDigit(...) to identify a digit and knitting a digit-only String which can later be parsed as an Integer,

Code Snippet:

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();
}

Input:

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

Output:

12345

You can also use String.replaceAll method.

Code snippet:

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);

    }
}

Output:

34556734
43512

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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