开发者

java string-manipulations

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));

    开发者_StackOverflow社区}

    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.


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.


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.


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;


}


  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.


String text = "This is a test";
String text2 = text.replaceAll(" is ", "is not");
System.out.println(text2);


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))); 
    }
}


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;
}
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜