Madhu
Madhu

Reputation: 1800

Search String with Arraylist in android

in my android application i have tried to compare string with arraylist check it out my below code

ArrayList<String> namelist = new ArrayList<String>();
        ArrayList<String> withoutcomma = new ArrayList<String>();

        namelist.add("chennai , In");
        namelist.add("mumbai, In");
        namelist.add("Usak,TR");
        namelist.add("Ushuaia,AR");
        namelist.add("San Francisco,US");

        for (int i = 0; i < namelist.size(); i++) {
            String[] value = namelist.get(i).split("\\s*,\\s*");
            withoutcomma.add(value[0]);
            withoutcomma.add(value[1]);
        }

        String name = "i want to go chennai to mumbai";
        String[] splitname = name.split(" ");

        for (int i = 0; i < splitname.length; i++) {
            if (withoutcomma.contains(splitname[i])) {
                System.out.println(splitname[i]);
            }
        }

it returns correct output

chennai 
mumbai

but not able to get the value for san fransisco because white space, i am totally struck, even i have used Pattern and matches but not able to handle the white space

Can anybody help ??

Upvotes: 2

Views: 390

Answers (3)

Samrat Dutta
Samrat Dutta

Reputation: 1737

Split the words at commas as well as at any spaces. So, when ever you get a multiple word place name, store it in the Array, and then use it to compare. works for me.

Use this :

    ArrayList<String> namelist = new ArrayList<String>();
    ArrayList<String> withoutcomma = new ArrayList<String>();

    namelist.add("chennai , In");
    namelist.add("mumbai, In");
    namelist.add("Usak,TR");
    namelist.add("Ushuaia,AR");
    namelist.add("San Francisco,US");

    for (int i = 0; i < namelist.size(); i++) {
        String[] value = namelist.get(i).split("[(\\s*,\\s*)\\s]");
        for(String word : value) {
            withoutcomma.add(word);
        }
    }

    String name = "i want to go San Francisco to mumbai";
    String[] splitname = name.split(" ");

    for (int i = 0; i < splitname.length; i++) {
        if (withoutcomma.contains(splitname[i])) {
            System.out.println(splitname[i]);
        }
    }

Upvotes: 2

Elmira Frhn
Elmira Frhn

Reputation: 320

you can use trim() to omit space in San Francisco,

change

 String[] value = namelist.get(i).split("\\s*,\\s*");

to

 String[] value = namelist.get(i).trim().split("\\s*,\\s*");

Upvotes: 1

milez
milez

Reputation: 2201

Instead of splitting by white space, you could look for values of your withoutcomma array in the String name.

for (String str : withoutcomma)
{
    if (name.contains(str))
    {
        System.out.println("Found city: " + str + " at position: " + name.indexOf(str));
    }
}

And if the order of the cities matters, you can save the index of the value that was found in String name with int idx = name.indexOf(str).

Upvotes: 2

Related Questions