how to check if a String has one word or two words

Hi

I have a string which have state name
like
Arizona
californinia
South carolina
North carolina

what I need is to check

if(state is one word{

get standard abbreviation

}
else
{

get first letter of both the words

}

Would anyone know how to do this

Any help will be greatly appreciated
huzefaqAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
CEHJConnect With a Mentor Commented:
You could keep a Map of states, then

                  Pattern p = Pattern.compile("^(.).+\\b(.).+");
                  Matcher m = p.matcher(inputString);
                  if (m.matches()) {
                        String letterOne = m.group(1);
                        String letterTwo = m.group(2);
                        System.out.printf("%s %s\n", letterOne, letterTwo);
                  }
                  else {
                        String state = stateMap.get(inputString);
                  }
0
 
Ajay-SinghCommented:
you can try this too,

if(state.indexOf(' ') > 0) {
// The state has more than 1 words.
}
else {
}

This works efficiently if the state has words seperated by one/more spaces
0
 
huzefaqAuthor Commented:
CEHJ Thanks

But

 System.out.printf("%s %s\n", letterOne, letterTwo);

this line is giving error

0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
huzefaqAuthor Commented:
Ajay-Singh

How can I get the first leter of both the words then
0
 
CEHJCommented:
>>System.out.printf("%s %s\n", letterOne, letterTwo);

You can delete that
0
 
RoyalNepalCommented:
You can do like this...too.



if (state.equals (""))//if state string is empty dont do anything
      return;

state = state.trim(); //takes out the spaces from first or last index

if(state.indexOf(' ') != -1)
{
  //return abbrev..it has only one word
}
else
{
//it has two words....so to take out the first letter..
//eg...if it has "South carolina" it returns South
  int index = state.indexOf(' ');
  return state.substring(0,index+1);
}

0
 
CEHJCommented:
:-)
0
All Courses

From novice to tech pro — start learning today.