3

How do I search a string array with start with keyword?

for example,

String[] str = { "abcd", "abdc", "bcda"};

when my search string is "a" it must show

abcd and abdc

when my search string is "abc" then it should be "abcd".

2
  • 5
    You loop over the array and compare the beginning of each entry with your search string. What have you tried? Show some code. Commented May 14, 2010 at 12:59
  • Is it sorted. And is there any reason you can't use something other than an array, like a TreeList? Commented May 14, 2010 at 13:20

2 Answers 2

8
String[] strArray = {"abcd", "abdc", "bcda"};
for (String s : strArray)
    if (s.startsWith(searchTerm))
        System.out.println(s);

Swap startsWith for contains you wish to simply look for containment.

Sign up to request clarification or add additional context in comments.

2 Comments

I agree, but just a side note that this is a case sensitive operation.
good point. Do s.toLowerCase().startsWith(searchTerm.toLowerCase()) to make it insensitive.
0

You should check this method:

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#contains%28java.lang.CharSequence%29

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.