gpt4 book ai didi

java - 如何使用索引将字符替换为字符串

转载 作者:行者123 更新时间:2023-12-01 23:11:58 26 4
gpt4 key购买 nike

嗨,用字符串替换字符的最佳方法是什么:例如:

就我而言,我有一个包含拉丁字符和符号的字符串,我正在使用 intermec 打印机打印它。我必须使用以下打印机传递字符的 ASCII 代码说明:

 instruction CHR$(<dec. ascii value>)

示例:此文本:N°Box 将像这样转换:

    "N\""+";CHR$(179); \""+"Box"

我写了这个:

if (!isValid(str)) {
Map charsAsciiCode = new HashMap();
for (int i = 0; i < str.length(); i++) {
String c = String.valueOf(str.charAt(i));
if (specialCharsMap.containsKey(c)) {
String decimalString = (String) specialCharsMap.get(c);
charsAsciiCode.put(new Integer(i), " \";CHR$(" + decimalString + ");\"");
}
}

Iterator iter = charsAsciiCode.entrySet().iterator();

while (iter.hasNext()) {
Map.Entry mapEntry = (Map.Entry) iter.next();
int charIndex = (int) mapEntry.getKey();
String charAscii = (String) mapEntry.getValue();

// Here i want to replace every char with the correspondant Ascii value
}
}

static boolean isValid(String input) {
Matcher m = p.matcher(input);
return m.matches();
}

final static Pattern p = Pattern.compile("\\p{Alpha}+");
private static Map specialCharsMap = new HashMap();

static {
specialCharsMap.put("é", "123");
specialCharsMap.put("è", "125");
specialCharsMap.put("à", "64");
specialCharsMap.put("ç", "92");
specialCharsMap.put("^", "94");
specialCharsMap.put("'", "39");
}

最佳答案

您不需要 map ,因为您可以执行以下操作:

StringBuilder sb = new StringBuilder();

for (int i = 0; i < str.length(); i = i+1) {
char ch = str.charAt(i);
if (ch > 127) {
// TODO: generate all the \\""+; crap around CHR$()
sb.append(String.format("CHR$(%d)", (int)ch));
}
else
sb.append ch;
}

关于java - 如何使用索引将字符替换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21796180/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com