1

I want to print \u0070\u0075\u0062 as output of this program, how can I do this in Java.

public class ankit {
    public static void main(String[]args){
        String s="\u0070\u0075\u0062";
        System.out.println(s);
    }
}

it gives me "pub" as output

actually i am sending it to a database and if there is unicode for new line charcter "\n" my bulk import to mySQL is not proper. so I want to store the string as unicode encoded when writing to mysql

i dont want to convert unicode for "\n" to actual newline while writing into db

Bharthan
  • 1,458
  • 2
  • 17
  • 29
  • 1
    I think it depends on the command prompt whether it will allow you to print Unicode chars on it!! – Harshit Oct 27 '15 at 03:47
  • actually i am sending it to a database and if there is unicode for new line charcter "\n" my bulk import to mySQL is not proper. so I want to store the string as unicode encoded when writing to mysql – Bharthan Oct 27 '15 at 03:56
  • Do you want to do this for all characters or for specific characters, ie. `\n`? You basically just want to escape some characters, not necessarily get their unicode representation. – Sotirios Delimanolis Oct 27 '15 at 04:12
  • yes I want it specifically for '\n', but while reading back from database I need to put back this '\n' in place. – Bharthan Oct 27 '15 at 04:14

2 Answers2

2

you can do like that:

  String s="\\u0070\\u0075\\u0062";

than you can get the ans

lin
  • 21
  • 3
  • This was what I thought first, but replacing '\' with '\\' is overhead and didn't serve my for my purpose. – Bharthan Oct 27 '15 at 04:01
1

This should help you do the trick :)

public class Test {
  public static void main(String[] args) {
    String s = "\u0070\u0075\u0062";
    StringBuffer sbuffer = new StringBuffer();
    for (int i = 0; i < s.length(); i++) {
      char ch = s.charAt(i);
      if (ch >= '\u0000' && ch <= '\u01FF') {
        String ss = Integer.toHexString(ch);
        sbuffer.append("\\\\u");
        for (int k = 0; k < 4 - ss.length(); k++) {
          sbuffer.append('0');
        }
        sbuffer.append(ss.toUpperCase());
      } else {
        sbuffer.append(ch);
      }
    }
    System.out.println(sbuffer);
  }
}

source : http://arpan-khandelwal-tech.blogspot.in/2008/08/this-article-is-related-to-escaping-of.html

Sudipta Mondal
  • 2,550
  • 1
  • 19
  • 20
  • it is converting all characters to unicode, I want to maintain that characters that are in unicode as unicode and characters that are not encoded as it is. ex: " \u0070\u0075\u0062 a b c d" should not return encoded value for abcd. – Bharthan Oct 27 '15 at 05:23