开发者

replacing a character every occurrence in a string in java

I'm suppose to replace a "L" in a string every time it is found in the string HELLO WORLD, with "x". and the x is to increased every occurrence of L.

input: "HELLO WORLD"
output: "开发者_开发百科HExxxO WORxxxD"

use only String methods: .length; .indexOf; .substring and .concat (or +).

EDIT

Here's my try:

public static String replace(String input,String pattern) { 

  String result = " "; 
  int stringLength; 
  int patternIndex; 

  while (input !=null) { 
    patternIndex = input.indexOf(pattern); 
    stringLength = input.length(); 
  } 

  return result; 
} 

i only find the index of the pattern and the length of the string having problem with replacing the character.


First: sane solution:

StringBuilder  sb = new StringBuilder();
StringBuilder   r = new StringBuilder();
for( char c : "HELLO LAZY LIMBO WORLD" .toCharArray() ) {
  if( c == 'L' ) {
     sb.append(r.append('x'));
  } else {
    sb.append( c );
  }
}
return sb.toString() );

Then modified to meed the criteria of only using valid methods .length; .indexOf; .substring and .concat (or +) ( removing toCharArray(); and StringBuilder )

public static String replace( String input ){ 
  String replacement = "";
  int iot = -1;
  while( ( iot = input.indexOf('L')) > -1 ) { 
    input = input.substring(0,iot) +
           ( replacement+='x' ) +
            input.substring(iot+1);
  }
  return input;
}

That one look like a for loop. Let's change it!

With only two statements ( declr and a for loop ):

public static String replace( String in ){     
  String x = "";
  for( int i = 0;  ( i = in.indexOf('L',i)) > -1 ; 
          in = in.substring(0,i++) + ( x=x+'x' ) + in.substring(i) );
  return in;
}

Yields:

HExxxO xxxAZY  xxxxIMBO WOxxxxxR

Now, that's! a for loop. I almost make Java look like perl.


static String xform(String helloWorld) {
    if (helloWorld.intern() != "HELLO WORLD")
        throw new IllegalArgumentException("bad World");

    return "HExxxO WORxxxD";
}

and here is a very special version for the ones w/o sense of humor: the special edition - loplez&funless

public class TheLoop {
  public static void main(String[] args) throws Throwable{
    System.out.println(xForm2("Hello World -L".toUpperCase(),0));
  }  
  static String xForm2(String s,int k){
    return k<-1?"x"+xForm2(s,k+1):(k==-1?"":("L".equals(s.substring(0,1))?xForm2(s,-(k+1)-1) :s.substring(0,1))+(s.length()==1?"":xForm2(s.substring(1), "L".equals(s.substring(0,1))?k+1:k)));
  }
}

200 bounty if anyone manages to write the function in a single line (single semicolon) and uglier than this


String x_ify(String input) {
    String output = "";
    int start = 0;
    int count = 0;
    int nextL;
    while ((nextL = input.indexOf('L', start)) >= 0) {
        if (nextL > start) {
            output = output + input.substring(start, nextL);
        }
        ++count;
        for (int i = 0; i < count; ++i) {
            output = output + "x";
        }
        start = nextL + 1;
    }
    if (start < input.length()) {
        output += input.substring(start);
    }
    return output;
}


       char charToReplace = 'l';
        String str = " Hello World";
        char newChar = 'x';
        String newString = "x";
        StringBuilder result = new StringBuilder();
        for (int index = 0; index < str.length(); index++) {
            if (str.charAt(index) == charToReplace) {
                result.append(newString);
                newString += newChar;
            } else {
                result.append(str.charAt(index));
            }
        }
        System.out.println(result);

Note: it can be optimized


A bodyless one-liner for statement, specially for bestsss:

public static String replace(String s) {
    for (String x="";  s.indexOf('L') > -1 ; s = s.substring(0,s.indexOf('L')) + ( x=x+'x' ) + s.substring(s.indexOf('L')+1) );
    return s;
}


Although not using the standard functions you mentioned but this is an alternate way:

public static void  first()
    {
        String input = "HELLO WORLD";
        String X = "";

        int numofL = input.length() - input.replaceAll("L+", "").length();


        for(int i=0;i<numofL;i++)
            X += "x";

        String output = input.replaceAll("L+", X);
        System.out.println(output);
    }


public static void main(String[] args) {
        String input = "HELLO WORLD";
        String output = "";
        String repl = "x";
        int idx, start = 0;
        while ((idx = input.indexOf('L', start)) > 0) {
            output += input.substring(start, idx);
            output += repl;
            start = idx + 1;
            repl += "x";
        }
        if (start < input.length()) {
            output += input.substring(start);
        }
        System.out.println(output);
    }


public class Main {

public static void main(String[] args) {
    System.out.println(replace("hello world", "x"));
}

public static String replace(String in, String xs) {
    return in.indexOf("l") != -1 ? replace(in.substring(0, in.indexOf("l")) + xs + in.substring(in.indexOf("l") + 1), xs + "x") : in;
}

}


public class ReplaceChar {

    public static void replaceChar(String s, StringBuilder sb, int depth){

        int i = s.indexOf('L');

        if(i==-1){
            return;
        }
        else
            sb.append(s.substring(0,i));
            for(int j=depth;j>0;j--){
                sb.append('x');
            }
            replaceChar(s.substring(i+1),sb,++depth);
    }

    public static void main(String[] args){

        StringBuilder sb = new StringBuilder();
        System.out.println("main "+sb);
        replaceChar("HELLO WORLD",sb,1);
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜