1

Ok, so I tried with your help to learn a little bit more about strings and Chaining Strings in Java.

now I know that strings are immutable, but I'm having a really hard time to do this ex:

Implement the method

public static String notReplace(String str)

The method takes a String as its input and returns a String in which every occurrence of the lowercase word "is" has been replaced with "is not". The word "is" should not 2 be immediately preceded or followed by a letter -- so for example the "is" in "this" should not be replaced. (Note: Character.isLetter(char) tests if a char is a letter.)

Examples:
notReplace("is test") → "is not test"
notReplace("is-is wise") → "is not-is not wise"

This is what I wrote:

public class NotReplace{

    public static void main(final String[] args){
        final String str2 = "is no";
        System.out.println(notReplace(str2));

    }

    public static String notReplace(final String str){
        final int times = str.length();

        final StringBuilder sb = new StringBuilder(str);
        for(int i = 0; i <= times; i++){
            if((str.charAt(i) == 'i') && (str.charAt(i + 1) == 's')
                && !Character.isLetter(str.charAt(i + 2))){
                sb.insert(i, "not");

            }
            final String str1 = sb.toString();
            return str1;

        }
    }
}

I believe it is a complete mess, I'll be happy to learn more how to work with strings in situations like this.

Thanks

Edit: I can't use replaceAll function.

12
  • After I have repaired indentation you can see that the return statement needs to be moved after the next closing curly brace Commented Mar 18, 2011 at 16:57
  • 1
    As it stands you will get IndexOutOfBoundsExceptions with this code. Commented Mar 18, 2011 at 16:58
  • @Dave: yeah, I know. can you give me some hints to correct it? Commented Mar 18, 2011 at 17:10
  • i<=times is vastly incorrect Commented Mar 18, 2011 at 17:18
  • @everyone it's labeled 'homework' so it should not touch reg exp, please don't offer 'em Commented Mar 18, 2011 at 17:19

8 Answers 8

4

You might find this interesting

String text = "This is a test. It is"; // note the 'is' at the end.
String text2 = text.replaceAll("\\bis\\b", "is not");
System.out.println(text +" => "+text2);

prints

This is a test. It is => This is not a test. It is not

The following method does this the long way

 public static String notReplace(final String str){
    final StringBuilder sb = new StringBuilder()
                                 .append(' ').append(str).append(" ");
    for (int i = 0; i < sb.length() - 2; i++) {
        if (!Character.isLetter(sb.charAt(i)) &&
                sb.charAt(i + 1) == 'i' &&
                sb.charAt(i + 2) == 's' &&
                !Character.isLetter(sb.charAt(i + 3))) {
            sb.insert(i + 3, " not");
            i += 5;
        }
    }
    return sb.substring(1, sb.length() - 1);
}

Spaces are added to the start and end to avoid bounds checking.

Sign up to request clarification or add additional context in comments.

3 Comments

Given that this is homework, I doubt OP would be allowed to use this.
Thanks peter, but I have to do that in the long way, I assume. I'll keep it in mind :)
Thank you. 1. you're using "insert" during the loop. How come it doesn't make a mess with the chacking?(or is this the reason that if the operand is true you add 5 to i?..) 2.strings, as arrays, start from 0? 3.For avoiding "is" in another words you added the initial operand that chacks whether the first char is not a letter?
3

I'd take the following approach if I were you.

First step: think of as many strings that are "curious" as you can: null, "", "i", "x", "is", "his", "ist", "list", "is it", "it is", "what is it", "what it is" and so on.

Second step: write a main() method that feeds all these values to the notReplace() method and displays the result. The notReplace() method should simply return the parameter at this point.

public static String notReplace(final String str){
  return str;
}

Third step. Compile and test it. This is an important one. Don't write large chunks of code at once. Write a little, recompile it and check whether it still works. It sounds slow but it is much quicker than rooting around for hours trying to find a mismatched curly brace in 200 lines of code. From now on, between each step you should repeat this.

Fourth step: change notReplace() so that it finds the "is" substring. Don't alter the output, just do a System.out.println( "Is found.");.

Fifth step: extend it even further by detecting whether the preceding and the following character (if there is any) is a letter or not.

Sixth step: insert " not" after where you've found "is".

If you follow these steps, you will be able to build your program up gradually and because you modify only a couple of lines between two tests, any errors will be easy to find.

Comments

1

Here is mine , quiet complicated but

public String notReplace(String str) {

  String result = "";

  if(str.equals("is")) return "is not";


  for(int i=0;i<str.length();i++){

    if((i+2 < str.length() && str.substring(i,i+2).equals("is") 
    && !Character.isLetter(str.charAt(i+2)) && (i==0 || !Character.isLetter(str.charAt(i-1)) )))
    {//for is that are in between texts and at the start of the text
      result += str.substring(i,i+2) + " not";
      result+=str.charAt(i+2);

      i = i + 2;

    }
    else if(i == str.length()-2 && str.substring(i).equals("is") && !Character.isLetter(str.charAt(i-1)) ){
        // for "is" at the end   
      result += str.substring(i,i+2) + " not";
      i = str.length();

    }
    else{// not a is
      result+= str.substring(i,i+1);
    }
  }
  return result;


}

Comments

0
  1. Problem is sb.insert(i, "not"); should be sb.insert(i+1, " not ");
  2. I think Regular Expression is a solution in such case.

2 Comments

The wording of the task implies that regular expressions shouldn't be used.
what do you mean by regular expressions?
0
String text = "This is a test";
String text2 = text.replaceAll(" is ", "is not");
System.out.println(text2);

1 Comment

Thanks, But I believe I cant use this in my h.w :)
0

Me, I like recursive:

public static String notReplace(String str) {

    StringBuilder buffer = new StringBuilder();
    notReplace(str, buffer);
    return buffer.toString();
}


public static void notReplace(String str, StringBuilder buffer) {
    if(str.length() < 3) {
        buffer.append(str).toString();
    }
    else if ( str.startsWith("is ") ) {
        notReplace(str.substring(3), buffer.append("is not "));         
    }
    else {
        notReplace(str.substring(1), buffer.append(str.charAt(0))); 
    }
}

Comments

0

public String notReplace(String str) {
  String outputStr = "";
  int index = 0;
  int lastSeen = 0;

  if (str == "is")
    return "is not";

  for (int i = 0; i < str.length() - 2; i++) {
    index = str.indexOf("is", lastSeen);
    if (index == -1)
      break;

    if (index == 0 && !Character.isLetter(str.charAt(index + 2))) {
      outputStr = outputStr + str.substring(lastSeen, index);
      outputStr = outputStr + "is not";
      lastSeen = index + 2;
    } else if (index > 0 && index < str.length() - 2 && str.charAt(index + 2) == ' ' && str.charAt(index - 1) == ' ') {
      outputStr = outputStr + str.substring(lastSeen, index);
      outputStr = outputStr + "is not";
      lastSeen = index + 2;
    } else if (index == (str.length() - 2) && !Character.isLetter(str.charAt(index - 1))) {
      outputStr = outputStr + str.substring(lastSeen, index);
      outputStr = outputStr + "is not";
      lastSeen = index + 2;
    } else {
      if (lastSeen < str.length()) {
        outputStr = outputStr + str.substring(lastSeen, index);
        outputStr = outputStr + "is";
      }
      lastSeen = index + 2;
    }

  }
  if (lastSeen < str.length())
    outputStr = outputStr + str.substring(lastSeen);
  return outputStr;
}
}

1 Comment

Do you think the first condition if (str == "is") is ever matching?
0
public String notReplace(String str) {
String a  = "";
int i = 0;
if(str.length()<2)
  {return "";}
else if(str.length()==2 && (!(str.substring(0).equals("is"))))
  {return "";}
else if(str.length()==2)
{return "is "+"not";}
while(i<str.length()){
if(i==0&& str.substring(0,2).equals("is")&&Character.isLetter(str.charAt(2))==false)
{a+= str.substring(0,2)+" not";
i+=2;}
else if(i>1&&i<str.length()-2&&str.substring(i,i+2).equals("is")&&Character.isLetter(str.charAt(i-1))==false&&Character.isLetter(str.charAt(i+2))==false)
{a+= str.substring(i,i+2)+" not";i+=2;}
else if(i == str.length()-2 && str.substring(str.length()-2).equals("is")&&Character.isLetter(str.charAt(str.length()-3))==false)
{a+=str.substring(str.length()-2)+ " not";break;}
else
{a+= str.charAt(i);
i+=1;}
}
return a;
}

this might seem complex but i got this in first try.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.