サロゲートペア文字(例えば????とか????)を含む文字列でStringBufferのreplaceメソッドを
使用したいのですが、replaceメソッドはサロゲートペア文字を考慮した実装ではないようで、
意図した挙動になりません。
lang
1StringBuffer sb = new StringBuffer("????の塩焼き"); 2sb.replace(0, 1, "鮭"); 3System.out.println(sb.toString());
期待している結果
鮭の塩焼き
実際の結果
鮭?の塩焼き
だいぶ強引に実装してみたのですが、そもそも既存のAPIやライブラリがあるよとか、
もっとシンプルに実装できるよとかあれば、教えて頂きたいです。
信頼性の面で、あまり独自実装したくありません。
宜しくお願いいたします。
lang
1String replace(String source, int start, int end, String replace) { 2 3 int codePointCount = 0; 4 5 List<String> targetList = new ArrayList<String>(); 6 codePointCount = source.codePointCount(0, source.length()); 7 for(int i=0;i<=codePointCount;i=source.offsetByCodePoints(i, 1)) { 8 int[] codePoint = new int[1]; 9 codePoint[0] = source.codePointAt(i); 10 targetList.add(new String(codePoint,0,1)); 11 } 12 if(start > codePointCount) { 13 throw new IndexOutOfBoundsException("start > codePointCount()"); 14 } 15 if(end > codePointCount) { 16 end = codePointCount; 17 } 18 19 List<String> replaceList = new ArrayList<String>(); 20 codePointCount = replace.codePointCount(0, replace.length()); 21 for(int i=0;i<codePointCount;i=replace.offsetByCodePoints(i, 1)) { 22 int[] codePoint = new int[1]; 23 codePoint[0] = replace.codePointAt(i); 24 replaceList.add(new String(codePoint,0,1)); 25 } 26 27 for(int i=start;i<end;i++) { 28 targetList.remove(start); 29 } 30 31 targetList.addAll(start, replaceList); 32 33 StringBuffer result = new StringBuffer(); 34 for(String s:targetList) { 35 result.append(s); 36 } 37 38 return result.toString(); 39}
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/07/10 12:03
2015/07/11 06:38