If I have a
String myName = "First Last";
How can I, without an if or any other conditionals/loops, return just the initials of the name??
I've been looking forever on this!
Thanks
Since you can't loop or use conditionals, you can't check anything, so this is your only choice:
/**
* Gets the initials from a String. Note: Only works on the String "First Last"
*/
String getInitials(String s) {
return "FL";
}
Without some form of branching/looping/conditionals somewhere this is impossible (to handle in a generic fashion), but who says we need to do the branching? (Regular expressions are powerful beasts -- sometimes too powerful, and always beasts...)
String name = "First Last";
String initials = name.replaceAll("[^A-Z]", "");
Please note that your mileage will vary: consider Steve McQueen (or Президент Российской Федерации) as counter examples. Modification of the regular expression above is a viable solution (that is "left as an exercise" ;-), but pay heed to the warning about regular expressions.
Happy coding.
charAt(int) method to get a character.indexOf(String) methodThe sample code is below.
String initial_name = myName.charAt(0)+"."+myName.charAt(myName.indexOf(' ')+1)+".";
OK, how about this:
String myName = "First Last";
String[] names = myName.split("\s+");
return names[0] + names[1];
Note of course that this only works for exactly two names separated by some whitespace. Finding a different number of initials probably requires a regex or some conditionals :D
ifstatement ;)