static String clean(String identifier) {
String firstString = "";
for (int i = 0; i < identifier.length(); i++)
if (Character.isISOControl(identifier.charAt(i))){
firstString = identifier.replaceAll(identifier.charAt(i),
"CTRL");
}
return firstString;
}
上面代码背后的逻辑是将字符串"标识符"中ISO控制字符的所有实例替换为"标识符";CTRL";。然而,我面临着这样的错误:;char不能转换为java.lang.String";
有人能帮助我解决和改进我的代码以产生正确的输出吗?
String#replaceAll需要一个String作为参数,但必须是正则表达式。请改用String#replace。
编辑:我还没有看到你想用一些字符串替换一个字符。在这种情况下,您可以使用这个版本的String#replace,但您需要将字符转换为字符串,例如使用character.toString.
更新
示例:
String text = "AB 03DE";
text = text.replace(Character.toString(' 03'), "CTRL");
System.out.println(text);
// gives: ABCTRLDE
代码点和控制图片字符
我可以补充两点:
char
类型自Java 2以来基本上已断开,遗留类型自Java 5以来基本上断开。使用单个字符时最好使用代码点整数- Unicode将要显示的字符定义为控制字符的占位符。请参阅一个维基百科页面的控制图片部分,并参阅另一个页面,Control Pictures
例如,代码点0小数处的NULL字符在9216小数处有一个匹配的SYMBOL For NULL字符:␀
。要查看所有控制图片字符,请使用Unicode标准规范的PDF部分。
获取表示字符串中每个字符的代码点整数数组。
int[] codePoints = myString.codePoints().toArray() ;
循环这些代码点。替换感兴趣的内容。
以下是一些未经测试的代码。
int[] replacedCodePoints = new int[ codePoints.length ] ;
int index = 0 ;
for ( int codePoint : codePoints )
{
if( codePoint >= 0 && codePoint <= 32 ) // 32 is SPACE, so you may want to use 31 depending on your context.
{
replacedCodePoints[ index ] = codePoint + 9_216 ; // 9,216 is the offset to the beginning of the Control Picture character range defined in Unicode.
} else if ( codePoint == 127 ) // DEL character.
{
replacedCodePoints[ index ] = 9_249 ;
} else // Any other character, we keep as-is, no replacement.
{
replacedCodePoints[ index ] = codePoint ;
}
i ++ ; // Set up the next loop.
}
将代码点转换回文本。使用StringBuilder#appendCodePoint
来构建文本的字符。您可以使用以下基于流的代码作为样板。有关解释,请参阅此问题。
String result =
Arrays
.stream( replacedCodePoints )
.collect( StringBuilder::new , StringBuilder::appendCodePoint , StringBuilder::append )
.toString();