简体   繁体   中英

How do I replace a unicode Character representing an emoji into a colon delimited String emoji?

I've got a JSON mapping all of the unicode emojis to a colon separated string representation of them (like twitter uses). I've imported the file into an ArrayList of Pair< Character, String> and now need to scan a String message and replace any unicode emojis with their string equivalents.

My code for conversion is the following:

  public static String getStringFromUnicode(Context context, String m) {
    ArrayList<Pair<Character, String>> list = loadEmojis(context);
    String formattedString="";
    for (Pair p : list) {
       formattedString  = message.replaceAll(String.valueOf(p.first), ":" + p.second + ":");
    }
    return formattedString;
}

but I always get the unicode emoji representation when I send the message to a server.

Any help would be greatly appreciated, thanks!!

When in doubt go back to first principles.

You have a lot of stuff that is all nested together. I have found in such cases that your best approach to solving the problem is to pull it apart and look at what the different pieces are doing. This lets you take control of the problem, and place test code where needed to see what the data is doing.

My best guess is that replaceAll() is acting unpredictably; misinterpreting the emoji string as commands for its regular expression analysis.

I would suggest substituting replaceAll() with a loop of your own that does the same thing. Since we are working with Unicode I would suggest going down deep on this one. This little code sample will do the same thing as replace all, but because I am addressing the string on a character by character basis it should work no matter what funny controls codes are in the string.

String message = "This :-) is a test :-) message";
String find = ":-)";
String replace = "!";
int pos = 0;

//Replicates function of replaceAll without the regular expression analysis
pos = subPos(message,find);
while (pos != -1)
{
   String tmp = message.substring(0,pos);
   tmp = tmp + replace;
   tmp = tmp + message.substring(pos+find.length());
   message = tmp;
   pos = subPos(message,find);
 }
System.out.println(message);


-- Snip --

//Replicates function of indexOf
public static int subPos(String str, String sub)
{
   for (int i = 0; i < str.length() - (sub.length() - 1); i++)
   {
      int j;
      for (j = 0; j < sub.length(); j++)
      {
         System.out.println(i + j);
         if (str.charAt(i + j) != sub.charAt(j))
            break;
      }
      if (j == sub.length()) 
         return i;
   }
   return -1;
}

I hope this helps. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM