-5

I want to return true if the first letter of a string alphabetically precedes the first letter of another string. So if s1 = "Adam" and s2 = "Bob" then s1.someMethod(s2) should return true since A comes before B in the alphabet. I just need a few lines to do this so maybe using charAt(0) first could be involved.

Cheers.

Sergey
  • 176
  • 2
  • 12
cornelius
  • 247
  • 1
  • 2
  • 9
  • first make them both capital or lower case to compare them more easily. then you take both chars and check which one is bigger – XtremeBaumer Apr 06 '17 at 06:09
  • *maybe using charAt(0) first could be involved.* That and the `<` operator is all you'll need. Did you make any effort at solving this on your own? – shmosel Apr 06 '17 at 06:10
  • http://stackoverflow.com/questions/6203411/comparing-strings-by-their-alphabetical-order – soorapadman Apr 06 '17 at 06:24

2 Answers2

3

You can do the following:

1. Convert the strings to lowercase

2. Compare their ASCII values of the first characters

    int diff=s1.charAt(0)-s2.charAt(0);

3. Print the result

    if(diff>0)

       return true;

    else 

       return false;
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
Pooja Arora
  • 574
  • 7
  • 19
1

s1.someMethod(s2) should return true

If you are already looking for a simple method, then String already implements Comparable interface, so you can simply use compareTo as shown below:

s1.compareTo(s2)<0

This will return true if s1 comes before s2 i.e., in the alphabetic order. Also, just to add, s1.compareTo(s2) returns 0 if both the strings are equal.

Vasu
  • 21,832
  • 11
  • 51
  • 67