Sunday 5 June 2016

wordEnds

Goto Problem

Given a string and a non-empty word string, return a string made of each char just before and just after every appearance of the word in the string. Ignore cases where there is no char before or after the word, and a char may be included twice if it is between two words.

wordEnds("abcXY123XYijk", "XY") → "c13i"
wordEnds("XY123XY", "XY") → "13"
wordEnds("XY1XY", "XY") → "11"
public String wordEnds(String str, String word)
 {
    String res="";
    if(word.equals(str))
       return res;
    if(str.startsWith(word)) 
    res=res+str.charAt(word.length());
    int i=1;
    while(i<(str.length()-word.length()))
   {
      if(str.substring(i).startsWith(word))
      {
         res=res+str.charAt(i-1)+str.charAt(i+word.length()); i=i+word.length();
       }
      else
       {
          i++;
       }
    }
    if(str.endsWith(word))
    {
        res=res+str.charAt(str.length()-word.length()-1);
        }
     return res;
 }

No comments:

Post a Comment