String – 2


doubleChar
Given a string, return a string where for every char in the original, there are two chars.
doubleChar(“The”) → “TThhee”
doubleChar(“AAbb”) → “AAAAbbbb”
doubleChar(“Hi-There”) → “HHii–TThheerree”

public String doubleChar(String str) {
      String str1 = "";
      for (int i = 0; i < str.length(); i++) {
          str1 = str1 + str.charAt(i) + str.charAt(i);
      }
      return str1;
  }

countHi
Return the number of times that the string “hi” appears anywhere in the given string.
countHi(“abc hi ho”) → 1
countHi(“ABChi hi”) → 2
countHi(“hihi”) → 2

public int countHi(String str) {
       int count = 0;
       for (int i = 0; i < str.length() - 1; i++) {
           if (str.substring(i, i + 2).equals("hi")) {
               count++;
           }
       }
       return count;
   }

catDog
Return true if the string “cat” and “dog” appear the same number of times in the given string.
catDog(“catdog”) → true
catDog(“catcat”) → false
catDog(“1cat1cadodog”) → true

public boolean catDog(String str) {
       int catCount = 0;
       int dogCount = 0;
       for (int i = 0; i < str.length() - 2; i++) {
           if (str.substring(i, i + 3).equals("cat")) {
               catCount++;
           }
           if (str.substring(i, i + 3).equals("dog")) {
               dogCount++;
           }
       }
       return catCount == dogCount;
   }

countCode
Return the number of times that the string “code” appears anywhere in the given string, except we’ll accept any letter for the ‘d’, so “cope” and “cooe” count.
countCode(“aaacodebbb”) → 1
countCode(“codexxcode”) → 2
countCode(“cozexxcope”) → 2

public int countCode(String str) {
        int count = 0;
        for (int i = 0; i < str.length() - 3; i++) {
            if (str.substring(i, i + 2).equals("co") && str.substring(i + 3, i + 4).equals("e")) {
                count++;
            }
        }
        return count;
    }

endOther
Given two strings, return true if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be “case sensitive”). Note: str.toLowerCase() returns the lowercase version of a string.
endOther(“Hiabc”, “abc”) → true
endOther(“AbC”, “HiaBc”) → true
endOther(“abc”, “abXabc”) → true

public boolean endOther(String a, String b) {
       a = a.toLowerCase();
       b = b.toLowerCase();
       if (a.length() <= b.length()) {
           if (b.substring(b.length() - a.length(), b.length()).equals(a)) {
               return true;
           }
       }
       if (a.length() >= b.length()) {
           if (a.substring(a.length() - b.length(), a.length()).equals(b)) {
               return true;
           }
       }
       return false;
   }

xyzThere
Return true if the given string contains an appearance of “xyz” where the xyz is not directly preceeded by a period (.). So “xxyz” counts but “x.xyz” does not.
xyzThere(“abcxyz”) → true
xyzThere(“abc.xyz”) → false
xyzThere(“xyz.abc”) → true

public boolean xyzThere(String str) {
       for(int i = 0; i<str.length()-2; i++ ){
           if(i==0 && str.substring(i, i+3).equals("xyz")){
               return true;
           }
           if(i > 1 && str.substring(i, i+3).equals("xyz") && str.charAt(i-1) !='.'){
               return true;
           }
       }
       return false;
   }

bobThere
Return true if the given string contains a “bob” string, but where the middle ‘o’ char can be any char.
bobThere(“abcbob”) → true
bobThere(“b9b”) → true
bobThere(“bac”) → false

public boolean bobThere(String str) {
      for(int i = 0; i<str.length()-2; i++){
          if(str.charAt(i) == 'b' && str.charAt(i+2) == 'b'){
              return true;
          }
      }
      return false;
  }

xyBalance
We’ll say that a String is xy-balanced if for all the ‘x’ chars in the string, there exists a ‘y’ char somewhere later in the string. So “xxy” is balanced, but “xyx” is not. One ‘y’ can balance multiple ‘x’s. Return true if the given string is xy-balanced.
xyBalance(“aaxbby”) → true
xyBalance(“aaxbb”) → false
xyBalance(“yaaxbb”) → false

public boolean xyBalance(String str) {
      if ((str.lastIndexOf("y") > str.lastIndexOf("x"))) {
          return true;
      }
      if (str.indexOf("x") == str.indexOf("y")) {
          return true;
      }
      return false;
  }

mixString
Given two strings, a and b, create a bigger string made of the first char of a, the first char of b, the second char of a, the second char of b, and so on. Any leftover chars go at the end of the result.
mixString(“abc”, “xyz”) → “axbycz”
mixString(“Hi”, “There”) → “HTihere”
mixString(“xxxx”, “There”) → “xTxhxexre”

public String mixString(String a, String b) {
     String result = "";
     int shorterAb = Math.min(a.length(), b.length());
     for (int i = 0; i < shorterAb; i++) {
         result = result + a.charAt(i) + b.charAt(i);
     }
     if (a.length() >= b.length()) {
         return result + a.substring(b.length(), a.length());
     }
     if (a.length() <= b.length()) {
         return result + b.substring(a.length(), b.length());
     }
     return result;
 }

repeatEnd
Given a string and an int n, return a string made of n repetitions of the last n characters of the string. You may assume that n is between 0 and the length of the string, inclusive.
repeatEnd(“Hello”, 3) → “llollollo”
repeatEnd(“Hello”, 2) → “lolo”
repeatEnd(“Hello”, 1) → “o”

public String repeatEnd(String str, int n) {
    String result = "";
    for (int i = 0; i < n; i++) {
        result = result + str.substring(str.length() - n, str.length());
    }
    return result;
}

repeatFront
Given a string and an int n, return a string made of the first n characters of the string, followed by the first n-1 characters of the string, and so on. You may assume that n is between 0 and the length of the string, inclusive (i.e. n >= 0 and n <= str.length()).
repeatFront(“Chocolate”, 4) → “ChocChoChC”
repeatFront(“Chocolate”, 3) → “ChoChC”
repeatFront(“Ice Cream”, 2) → “IcI”

public String repeatFront(String str, int n) {
       String result = "";
       for (int i = 0; i < n; i++) {
           result = result + str.substring(0, n - i);
       }
       return result;
   }

repeatSeparator
Given two strings, word and a separator sep, return a big string made of count occurrences of the word, separated by the separator string.
repeatSeparator(“Word”, “X”, 3) → “WordXWordXWord”
repeatSeparator(“This”, “And”, 2) → “ThisAndThis”
repeatSeparator(“This”, “And”, 1) → “This”

public String repeatSeparator(String word, String sep, int count) {
       String result = "";
       for(int i = 0; i<count; i++){
           if(count == 1){
               return word;
           }
           result = result + word+sep;
       }
       return result.substring(0, result.length()-sep.length());
   }

prefixAgain
Given a string, consider the prefix string made of the first N chars of the string. Does that prefix string appear somewhere else in the string? Assume that the string is not empty and that N is in the range 1..str.length().
prefixAgain(“abXYabc”, 1) → true
prefixAgain(“abXYabc”, 2) → true
prefixAgain(“abXYabc”, 3) → false

public boolean prefixAgain(String str, int n) {
        String prefix = str.substring(0, n);
        for (int i = 0; i < str.length() - n + 1; i++) {
            if (i >= n && prefix.equals(str.substring(i, i + n))) {
                return true;
            }
        }
        return false;
    }

xyzMiddle
Given a string, does “xyz” appear in the middle of the string? To define middle, we’ll say that the number of chars to the left and right of the “xyz” must differ by at most one. This problem is harder than it looks.
xyzMiddle(“AAxyzBB”) → true
xyzMiddle(“AxyzBB”) → true
xyzMiddle(“AxyzBBB”) → false

public boolean xyzMiddle(String str) {
       int front = 0;
       int end = 0;
       int res = 0;
       for (int i = 0; i < str.length() - 2; i++) {
           if (str.length() >= 3 && str.substring(i, i + 3).equals("xyz")) {
               front = str.substring(0, i).length();
               end = str.substring(i + 3, str.length()).length();
               res = front - end;
               if (Math.abs(res) <= 1) {
                   return true;
               }
           }
       }
       return false;
   }

getSandwich
A sandwich is two pieces of bread with something in between. Return the string that is between the first and last appearance of “bread” in the given string, or return the empty string “” if there are not two pieces of bread.
getSandwich(“breadjambread”) → “jam”
getSandwich(“xxbreadjambreadyy”) → “jam”
getSandwich(“xxbreadyy”) → “”

public String getSandwich(String str) {
       for (int i = 0; i<str.length()-4; i++){
           if(str.length()>=5 && str.substring(i, i+5).equals("bread")){
               if(str.lastIndexOf("bread") != -1 &&  i+5 < str.lastIndexOf("bread")){
                   return str.substring(i+5, str.lastIndexOf("bread") );
               }
           }
       }
       return "";
   }

sameStarChar
Returns true if for every ‘*’ (star) in the string, if there are chars both immediately before and after the star, they are the same.
sameStarChar(“xy*yzz”) → true
sameStarChar(“xy*zzz”) → false
sameStarChar(“*xa*az”) → true

public boolean sameStarChar(String str) {
        int countTrue = 0;
        int countStar = 0;
        for (int i = 1; i < str.length() - 1; i++) {
            if (str.charAt(i) == '*' && str.charAt(i - 1) == str.charAt(i + 1)) {
                countTrue++;
            }
            if (str.charAt(i) == '*') {
                countStar++;
            }
        }
        return countStar == countTrue;
    }

oneTwo
Given a string, compute a new string by moving the first char to come after the next two chars, so “abc” yields “bca”. Repeat this process for each subsequent group of 3 chars, so “abcdef” yields “bcaefd”. Ignore any group of fewer than 3 chars at the end.
oneTwo(“abc”) → “bca”
oneTwo(“tca”) → “cat”
oneTwo(“tcagdo”) → “catdog”

public String oneTwo(String str) {
       String res = "";
       for (int i = 0; i < str.length() - 2; i++) {
           if (i % 3 == 0) {
               res = res + str.substring(i + 1, i + 3) + str.charAt(i);
           }
       }
       return res;
   }

zipZap
Look for patterns like “zip” and “zap” in the string — length-3, starting with ‘z’ and ending with ‘p’. Return a string where for all such words, the middle letter is gone, so “zipXzap” yields “zpXzp”.
zipZap(“zipXzap”) → “zpXzp”
zipZap(“zopzop”) → “zpzp”
zipZap(“zzzopzop”) → “zzzpzp”

public String zipZap(String str) {
        String result = "";
        if (str.length() >= 3) {
            for (int i = 0; i < str.length() - 2; i++) {
                result = result + str.charAt(i);
                if (str.charAt(i) == 'z' && str.charAt(i + 2) == 'p') {
                    result = result + "p";
                    i += 2;
                }
            }
            if (result.equals(str.substring(0, str.length() - 2))) {
                return str;
            }
            return result;
        }
        return str;
    }
    /*-----------------regex solution-------------------
     return str.replaceAll("z.p", "zp");*/

starOut
Return a version of the given string, where for every star (*) in the string the star and the chars immediately to its left and right are gone. So “ab*cd” yields “ad” and “ab**cd” also yields “ad”.
starOut(“ab*cd”) → “ad”
starOut(“ab**cd”) → “ad”
starOut(“sm*eilly”) → “silly”

public String starOut(String str) {
       String result = "";
       result = str.replaceAll(".\\*+.", "");
       result = result.replaceAll(".\\*", "");
       result = result.replaceAll("\\*.", "");
       result = result.replaceAll("\\*", "");
       return result;
   }

plusOut
Given a string and a non-empty word string, return a version of the original String where all chars have been replaced by pluses (“+”), except for appearances of the word string which are preserved unchanged.
plusOut(“12xy34”, “xy”) → “++xy++”
plusOut(“12xy34”, “1”) → “1+++++”
plusOut(“12xy34xyabcxy”, “xy”) → “++xy++xy+++xy”

public String plusOut(String str, String word) {
       String res = "";
       int wordLen = word.length();
       if (str.indexOf(word) != -1) {
           for (int i = 0; i < str.length() - wordLen + 1; i++) {
               if (!str.substring(i, i + wordLen).equals(word)) {
                   res += "+";
               }
               if (str.substring(i, i + wordLen).equals(word)) {
                   res = res.substring(0, res.length()) + word;
                   if (str.substring(i + wordLen, str.length()).indexOf(word) != -1) {
                       i += wordLen - 1;
                   }
               }
           }
           return res;
       }
       return str;
   }

wordEnds
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 (str.equals(word + word)) {
           return "" + str.charAt(0) + str.charAt(str.length() - 1);
       }
       if (str.indexOf(word) != -1 && str.length() > word.length()) {
           for (int i = 0; i < str.length() - word.length() + 1; i++) {
               if (i == 0) {
                   if (str.substring(i, word.length()).equals(word)) {
                       if (!str.substring(i + word.length(), i + (2 * word.length())).equals(word)) {
                           res += str.charAt(i + word.length());
                       }
                   }
               }
               if (i > 0) {
                   if (str.substring(i, i + word.length()).equals(word)) {
                       res = res.substring(0, res.length()) + str.charAt(i - 1);

                       if (str.length() > i + word.length()) {
                           res = res.substring(0, res.length()) + str.charAt(i + word.length());
                       }
                   }
               }
           }
           return res;
       }
       return "";
   }

Dodaj komentarz

Twój adres email nie zostanie opublikowany. Pola, których wypełnienie jest wymagane, są oznaczone symbolem *