Monday, February 20, 2012

insert a character before and after evrey letter in a string


i want to insert a % character before after every letter in a string , but using StringBuilder to make it fast.



for example,



if a string is 'AA'




then it would be '%A%A%'



if it is 'XYZ'




then it would be '%X%Y%Z%'

6 comments:

  1. String foo = "VWXYZ";
    foo = "%" + foo.replaceAll("(.)","$1%");
    System.out.println(foo);


    Output:


    %V%W%X%Y%Z%


    You don't need a StringBuilder. The compiler will take care of that simple concatenation prior to the regex for you by using one.

    Edit in response to comment below:

    replaceAll() uses a Regular Expression (regex).

    The regex (.) says "match any character, and give me a reference to it" . is a wildcard for any character, the parenthesis create the backreference. The $1 in the second argument says "Use backreference #1 from the match".

    replaceAll() keeps running this expression over the whole string replacing each character with itself followed by a percent sign, building a new String which it then returns to you.

    ReplyDelete
  2. string str="AA";
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < str.length(); s++)
    {
    sb.append("%");
    sb.append(str.charAt(i));
    }
    sb.append("%");


    This is the simpliest way to do that.

    ReplyDelete
  3. Try something like this:

    String test = "ABC";
    StringBuilder builder = new StringBuilder("");
    builder.append("%");
    for (char achar : test.toCharArray()) {
    builder.append(achar);
    builder.append("%");
    }
    System.out.println(builder.toString());

    ReplyDelete
  4. public static String escape(String s) {
    StringBuilder buf = new StringBuilder();
    boolean wasLetter = false;
    for (char c: s.toCharArray()) {
    boolean isLetter = Character.isLetter(c);
    if (isLetter && !wasLetter) {
    buf.append('%');
    }
    buf.append(c);
    if (isLetter) {
    buf.append('%');
    }
    wasLetter = isLetter;
    }
    return buf.toString();
    }

    ReplyDelete
  5. StringBuilder sb = new StringBuilder("AAAAAAA");

    for(int i = sb.length(); i >= 0; i--)
    {
    sb.insert(i, '%');
    }

    ReplyDelete
  6. You may see this.

    String s="AAAA";
    StringBuilder builder = new StringBuilder();
    char[] ch=s.toCharArray();
    for(int i=0;i<ch.length;i++)
    {
    builder.append("%"+ch[i]);
    }
    builder.append("%");
    System.out.println(builder.toString());


    Output

    %A%A%A%A%

    ReplyDelete