Java:使用 String.indexOf() 检查撇号字符



我正在尝试解析一个字符串,我需要使用子字符串来做到这一点。字符串包含撇号字符。我的问题是,如何使用 temp 获取 String.indexOf 来获取撇号字符的索引?

//temp variable currently contains the string 'hello' including the apostrophe character
String finalWord = temp.substring(temp.indexOf('''), temp.indexOf('.')); 

你的变量名是错误的(final是一个保留字),你应该使用转义字符:

String finalword = temp.substring(temp.indexOf('''), temp.indexOf('.')); 

根据你的最后一条评论,它声明了你实际想要做的事情......

有一个简单的单行解决方案,用于从输入中提取每个撇号引号字符串:

String[] quotedStrings = input.replaceAll("^.*?'|'[^']*$", "").split("'.*?('|$)");

下面是一些测试代码:

public static void main(String[] args) {
    String input = "xxx'foo'xxx'bar'xxx'baz'xxx";
    String[] quotedStrings = input.replaceAll("^.*?'|'[^']*$", "").split("'.*?('|$)");
    System.out.println(Arrays.toString(quotedStrings));
}

输出:

[foo, bar, baz]

最新更新