title: How to remove surrogate characters in Java?
body: <p>I am facing a situation where i get Surrogate characters in text that i am saving to MySql 5.1.  As the UTF-16 is not supported in this, I want to remove these surrogate pairs manually by a java method before saving it to the database.</p>
  
  <p>I have written the following method for now and I am curious to know if there is a direct and optimal way to handle this.  </p>
  
  <p>Thanks in advance for your help.</p>
  
  <pre><code>public static String removeSurrogates(String query) {
      StringBuffer sb = new StringBuffer();
      for (int i = 0; i &lt; query.length() - 1; i++) {
          char firstChar = query.charAt(i);
          char nextChar = query.charAt(i+1);
          if (Character.isSurrogatePair(firstChar, nextChar) == false) {
              sb.append(firstChar);
          } else {
              i++;
          }
      }
      if (Character.isHighSurrogate(query.charAt(query.length() - 1)) == false
              &amp;&amp; Character.isLowSurrogate(query.charAt(query.length() - 1)) == false) {
          sb.append(query.charAt(query.length() - 1));
      }
  
      return sb.toString();
  }
  </code></pre>