CodingBat: Java. String-2, Part II


For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


repeatFront:

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

repeatSeparator:

public String repeatSeparator(String word, String sep, int count) {
	String res = "";
	if (count == 0) return "";
	while (count > 1) {
		res += word + sep;
		count--;
	}
	return res + word;
}

prefixAgain:

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


<b>xyzMiddle:</b>
[sourcecode language="Java" gutter="false"]
public boolean xyzMiddle(String str) {
	int len = str.length();
	if (len < 3) return false;
	if (len % 2 == 1)
		return str.substring(len/2 - 1, len/2 + 2).equals("xyz");
	return str.substring(len/2 - 2, len/2 + 1).equals("xyz") 
			|| str.substring(len/2 - 1, len/2 + 2).equals("xyz");
}  
&#91;/sourcecode&#93;

<b>getSandwich:</b>
[sourcecode language="Java" gutter="false"]
public String getSandwich(String str) {  
	int first = str.indexOf("bread");
	int last = str.lastIndexOf("bread");
	if (first == last) return "";
	return str.substring(first+5, last);
}

sameStarChar:

public boolean sameStarChar(String str) {  
	for (int i = 1; i < str.length()-1; i++)
		if (str.charAt(i) == '*' && str.charAt(i-1) != str.charAt(i+1))
			return false;
	return true;
}
&#91;/sourcecode&#93;


<b>zipZap:</b>
[sourcecode language="Java" gutter="false"]
public String zipZap(String str) {
	for (int i = 0; i < str.length()-2; i++)
		if (str.charAt(i) == 'z' && str.charAt(i+2) == 'p')
			str = str.substring(0,i+1) + str.substring(i+2);
	return str;
}
&#91;/sourcecode&#93;

<b>starOut:</b>
[sourcecode language="Java" gutter="false"]
public String starOut(String str) {	
	while (str.indexOf('*') != -1) {
		if (str.equals("*")) return "";
		int starPos = str.indexOf('*');
		int secondStar = str.indexOf('*', starPos+1);
		if (secondStar - starPos == 1) {
			str = str.substring(0,starPos) + str.substring(secondStar);
			continue;
		}
		if (starPos == 0) str = str.substring(starPos+2);
		else if (starPos == str.length()-1)
			str = str.substring(0, str.length()-2);
		else str = str.substring(0, starPos-1) + str.substring(starPos+2);
	}
	return str;
}

plusOut:

public String plusOut(String str, String word) {
	int start = 0;
	int end = str.indexOf(word);
	while (end != -1) {
		for (int i = start; i < end; i++)
			str = str.substring(0,i) + "+" + str.substring(i+1);
		start = end + word.length();
		end = str.indexOf(word, start);
	}
	for (int i = start; i < str.length(); i++)
		str = str.substring(0,i) + "+" + str.substring(i+1);
	return str;
}&#91;/sourcecode&#93;

<b>wordEnds:</b>
[sourcecode language="Java" gutter="false"]
public String wordEnds(String str, String word) {
	String res = "";
	int pos = str.indexOf(word);
	while (pos != -1) {
		if (pos != 0) res += str.charAt(pos-1);
		if (pos + word.length() == str.length()) break; 
		res += str.charAt(pos + word.length());
		pos = str.indexOf(word, pos+1);
	}
	return res; 
}

For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


24 thoughts on “CodingBat: Java. String-2, Part II

  1. Maxim

    I don’t think you’re supposed to use more than 1 loop in the String-2 problem section. This is my solution for plusOut:

    public String plusOut(String str, String word) {
    String res = “”;
    int found = str.indexOf(word);

    for (int i = 0; i < str.length(); i++) {
    if (i == found) {
    res += word;
    found = str.indexOf(word, found + word.length());
    i += word.length()-1;
    } else {
    res += "+";
    }
    }

    return res;
    }

    Reply
    1. Simon Lahn

      Here’s my solution using the equals method. It requires one less variable.

      public String plusOut(String str, String word) {
      String result = “”;

      for (int i = 0; i < str.length(); i++) {
      //ensure there is no out of bounds and compare substring with word
      if(i + word.length() <= str.length() && str.substring(i, i + word.length()).equals(word)){
      result += word;

      //increment i by word length minus one since the for loop already increments i by 1
      i += word.length() – 1;
      }
      //Otherwise add a "+" and continue to increment i
      else
      result += "+";
      }

      return result;
      }

      Reply
  2. Stephan

    I don’t see an answer for the program oneTwo.
    Here is what i got:
    public static String oneTwo(String str) {
    String result = “”;

    for (int i = 0; i < str.length() – 2; i++) {
    if (i == 0 || i % 3 == 0) {
    result += str.substring(i + 1, i + 3);
    result += str.charAt(i);
    }
    }
    return result;

    Reply
    1. Chau Nguyen

      You can do this instead!

      public String oneTwo(String str) {
      if (str.length() < 3) return ""; // this part doesn't matter too much

      String result = "";

      for (int i = 0; i < str.length() – 2; i += 3)
      result = result + str.substring(i + 1, i + 3) + str.substring(i, i + 1);

      return result;
      }

      Reply
  3. Dave

    for prefix again i just used one return function:

    return(str.lastIndexOf(str.substring(0,n)) != str.indexOf(str.substring(0,n)));

    Reply
      1. Gregor Ulm Post author

        This is about as unreadable than the version of Dave. When you start out with programming, you may want to avoid picking up bad habits, such as questionable conciseness.

        Reply
  4. nick woodward

    Hi,

    Would you mind explaining your solution to starOut a little please? I’m struggling to follow it.

    Here’s my version:

    public String starOut(String str) {
    String temp = “”;

    for(int x = 0; x < str.length(); x++){
    //check previous
    if(x != 0 && str.charAt(x-1) == '*') continue;
    //check next
    if(x+1 < str.length() && str.charAt(x+1)=='*') continue;
    //check current
    temp += str.charAt(x)=='*'? "":str.charAt(x);
    }
    return temp;
    }

    Regards,

    Reply
  5. nick woodward

    just working through your ‘wordEnds’ solution too. nice.

    any thoughts on this way? (other than the tertiary operator being a little less legible)

    public String wordEnds(String str, String word) {
    String temp = “”;

    for(int x = 0; x < str.length(); x++){
    //check previous
    if(x != 0 && x + word.length() <= str.length())
    temp += str.substring(x,x+word.length()).equals(word)? str.substring(x-1,x):"";

    if(x + word.length()+1 <= str.length()){
    //check next
    temp += str.substring(x,x+word.length()).equals(word)? str.substring(x+ word.length(),x+word.length()+1):"";
    }
    } return temp;
    }

    regards,

    nick

    Reply
    1. Gelo

      we have almost same idea. here’s my solution:
      public String wordEnds(String str, String word) {

      String snip = “”;
      for(int i=0; i<str.length()-word.length()+1; i++){
      String s = str.substring(i, i+word.length());

      if(i != 0 && s.equals(word)){
      String s2 = str.substring(i-1, i);
      snip += s2;
      }

      if(i != str.length()-word.length() && s.equals(word)){
      String s3 = str.substring(i+word.length(), i+word.length()+1);
      snip += s3;
      }
      }
      return snip;
      }

      Reply
  6. Suraj

    I have another solution to plusOut
    public String plusOut(String str, String word) {

    char[] arr = str.toCharArray();
    Arrays.fill(arr,’+’);

    for(int i = 0 ; i < str.length() – word.length() +1 ; i++){
    if(str.substring(i , i + word.length()).equals(word)){
    int p = i;
    for(int k = 0 ; k < word.length() ; k++)
    arr[p++] = word.charAt(k);
    }
    }
    return new String(arr);
    }

    Reply
  7. Suraj

    starOut : Another solution

    public String starOut(String str) {
    return str.replaceAll(“.?\\*+.?”,””);
    }

    Note : .?\\*+.?
    .? => zero or one character (for boundary cases)
    \\*+ => one or more star

    Reply
    1. Gregor Ulm Post author

      If I recall correctly, replaceAll() is not part of the methods Nick Parlante mentions on the Coding Bat website. Thus, using it defeats the purpose of the exercise.

      Reply
  8. Kyran

    For prefixAgain, couldn’t you just avoid looping altogether with this? Bit of a newb, but I figure it’d be quicker to run (marginally)

    public boolean prefixAgain(String str, int n) {
    boolean res = false;
    String s = str.substring(0,n);

    if (str.lastIndexOf(s)>=n)
    {
    res = true;
    }
    return res;
    }

    Reply
  9. Simon

    I look at these solutions only after I’ve figured it out on my own only to realize I tend to over complicate the problem. What takes me 10+ lines, you manage to do in four lines. Thanks for the solutions.

    Reply
  10. Wojtek

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

    Reply
  11. Wojtek

    My solution

    public boolean prefixAgain(String str, int n) {
    String end = str.substring(n);
    return end.contains(str.substring(0,n));
    }

    Reply
  12. Wojtek

    My solution

    public String getSandwich(String str) {
    if(str.length()<=10) return "";
    return str.substring(str.indexOf("bread")+5,str.lastIndexOf("bread"));
    }

    Reply

Leave a Reply to kevin Cancel reply

Your email address will not be published. Required fields are marked *

Spammer prevention; the answer is an integer: * Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.