0

我正在使用 indexOf 在字符串中寻找终止符。

// character codes to look for
int[] defseps = new int[] {10, 13, 34, 36, 38, 39,41, 44, 59, 63, 93, 125};
int t = 999999999;  // big number,  We want first terminator 
int tempt = 0;

// loop through possible terminators
for (int x = 0; x < 12; x++) {
    tempt=str.indexOf(defseps[x]); // Get index of terminator
    if (defsepactivated[x] && tempt!=-1) {  // If active terminator found
        System.out.println("defsep used=" + defseps[x]);
        if (tempt < t) t = tempt; // Use this terminator if before previous found  
    }
}

此代码查找像 & (38) 和 ] (93) 这样的终止符,但不查找双引号 (34)。

例如,如果 str 是 : =THINGTHUNG";copyright ©它会找到分号和 & 但不是双引号。

非常感谢为什么在我尝试其他编码之前会出现这种情况。

4

1 回答 1

0

假设您要查找字符串中任何一个“终止符”字符的第一次出现的索引,请使用字符的字符类正则表达式:

if (!str.matches(".*[\n\r\"#&'),;?\\]}].*")) {
    // handle not found
} else {
    int t = str.split("[\n\r\"#&'),;?\\]}]")[0].length - 1;
}

仅供参考,大多数字符在字符类中失去其特殊的正则表达式含义并且不需要转义,但当然](关闭字符类)必须转义。

于 2014-11-11T20:39:08.400 回答