StringTools { public static String getWords(final String sentanceToTrim, int numOfWords) { String returnSentance = sentanceToTrim; int numSpaces = StringUtils.countMatches(sentanceToTrim, " "); LOG.trace("Found {} space(s) in '{}', want {} word(s).", numSpaces, sentanceToTrim, numOfWords); if (numSpaces > 0 && numSpaces >= numOfWords) { if (numSpaces > numOfWords) { LOG.trace("Number of spaces limited to {}", numOfWords); numSpaces = numOfWords; } int pos = -1; for (int i = 1; i <= numSpaces; i++) { pos = sentanceToTrim.indexOf(' ', pos + 1); } returnSentance = sentanceToTrim.substring(0, pos); LOG.trace("Final: '{}'", returnSentance); } return returnSentance; } private  StringTools(); static String characterMapReplacement(Character charToReplace); static String stringMapReplacement(String stringToReplace); static String appendToPath(final String basePath, final String additionalPath); static String cleanString(String sourceString); static String formatFileSize(long fileSize); static boolean isNotValidString(String testString); static boolean isValidString(String testString); static String trimToLength(String sourceString, int requiredLength); static String trimToLength(String sourceString, int requiredLength, boolean trimToWord, String endingSuffix); static List<T> castList(Class<? extends T> objClass, Collection<?> c); static List<String> splitList(String stringToSplit, String regexDelim); static String[] tokenizeToArray(String sourceString, String delimiter); static String processMpaaCertification(String mpaaCertification); static String processMpaaCertification(String mpaaRated, String mpaaCertification); static String replaceQuotes(String original); static int parseRating(String rating); static int parseRating(float rating); static String getWords(final String sentanceToTrim, int numOfWords);  }
@Test public void testGetWords() { LOG.info("getWords"); String result = StringTools.getWords("This is a test sentance", 2); assertEquals("This is", result); result = StringTools.getWords("Single", 2); assertEquals("Single", result); result = StringTools.getWords("Single", 1); assertEquals("Single", result); result = StringTools.getWords("Test sentance", 5); assertEquals("Test sentance", result); }