StringUtilities.java 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. public class StringUtilities {
  2. public Character getMiddleCharacter(String word){
  3. char[] character = word.toCharArray();
  4. int len = (character.length) / 2;
  5. if(character.length % 2 == 0)
  6. {
  7. return character[len];
  8. } else {
  9. return character[len];
  10. }
  11. }
  12. public String removeCharacter(String value, char charToRemove){
  13. //store input at the time this is called
  14. String n = value;
  15. //convert the to be removed char to a string
  16. String charString = String.valueOf(charToRemove);
  17. //replace the char with an empty string - removing it from the string
  18. //if there is nothing to remove, this function will return the original string
  19. n = searchReplaceFirst(n , charString, "");
  20. //if n is now still the same as the starting value, this means nothing could be replaced
  21. if(n.equals(value)){
  22. //return n since all occurences have been removed
  23. return n;
  24. //if n is now different from value, after the char has been replaced, recall this method.
  25. }else{
  26. //convert the string back to a character
  27. char remove = charString.charAt(0);
  28. //recursivly call this function on the updated string
  29. return removeCharacter(n, remove);
  30. }
  31. }
  32. public static String searchReplaceFirst(String value, String replace, String replacement){
  33. //if the two values are the same after something has been replaced, this means nothing has been replaced
  34. if(value.equals(value.replaceFirst(replace, replacement)))
  35. {
  36. //so return the original string
  37. return value;
  38. //otherwise, this means something has been replaced
  39. } else {
  40. //return the new value
  41. return value.replaceFirst(replace, replacement);
  42. }
  43. }
  44. public String getLastWord(String value) {
  45. String[] result = value.split(" ");
  46. return result[result.length - 1];
  47. }
  48. }