Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从字符串中删除引号中的子字符串?(不含正则表达式)_Java_String - Fatal编程技术网

Java 如何从字符串中删除引号中的子字符串?(不含正则表达式)

Java 如何从字符串中删除引号中的子字符串?(不含正则表达式),java,string,Java,String,我有一个包含以下内容的文本文件: 鲍勃去商店买牛奶买牛奶 我想删除string1中所有引用的材料,使其只包含:Bob去商店买牛奶 有没有一种不用正则表达式就可以做到这一点的方法?我目前正在尝试使用split方法。我首先使用split将文本文件读入名为string1的字符串变量,然后将值存储回名为newString的新字符串中 String string1 = new Scanner(new File("C:/bob.txt")).useDelimeter("\\A").next();

我有一个包含以下内容的文本文件: 鲍勃去商店买牛奶买牛奶

我想删除string1中所有引用的材料,使其只包含:Bob去商店买牛奶


有没有一种不用正则表达式就可以做到这一点的方法?我目前正在尝试使用split方法。我首先使用split将文本文件读入名为string1的字符串变量,然后将值存储回名为newString的新字符串中

String string1 = new Scanner(new File("C:/bob.txt")).useDelimeter("\\A").next();       
String newString = "";

String[] arr = string1.split("\"");
for (int i=0; i<arr.length-1; i++){
    newString += arr[y];
}
我对java非常陌生,不确定是否正确使用了split方法。当我打印新闻时,上面写着鲍勃去商店买牛奶

我的问题是应该说鲍勃去商店买牛奶。字符串缺少结尾的句点,它会写入存储两次

有人能帮我做这件事吗?如果有比拆分更好的方法,我想知道。我也希望它能为任何引用节数的字符串工作。也没有模式匹配/正则表达式,谢谢

您可以使用Java 8的流通过字符串的字符数组进行流处理,并通过过滤器跳过双引号,例如:

另一种方法是简单地在char数组中循环并跳过双引号,例如:

String s = "Bob blah blah \"quote\" blah \"another quote\"";
System.out.println(s);
StringBuilder s1 = new StringBuilder();
for(char c : s.toCharArray()){
    if(c != '"'){
        s1.append(c);
    }
}
System.out.println(s1.toString());
这将有助于:

public static void main(String[] args) {
    String str = "Bob went to \"the store\" the store to \"buy milk\" buy milk.";
    boolean inQuotes = false;
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < str.length(); i++) {
        if (str.charAt(i) == '"') inQuotes = !inQuotes;
        else if (!inQuotes) sb.append(str.charAt(i));
    }
    System.out.println(sb.toString());
}

注意,结果鲍勃去商店买牛奶。在去商店和买牛奶之间有两个空格,因为它只是删除了报价之间的内容。

为什么不使用正则表达式?我会建议使用StringreplaceAll方法,但它使用正则表达式。我目前正在尝试使用split方法split使用正则表达式…arshajii,这是期中考试的惯例。我们希望能够在使用和不使用regext的情况下执行此操作。这很好,但是我可以将变量sb从StringBuilder转换为String吗?我问这个问题的原因是,通过调用StringBuilder.toString,StringTokenizer之类的东西无法在sbConvert上工作
public static void main(String[] args) {
    String str = "Bob went to \"the store\" the store to \"buy milk\" buy milk.";
    boolean inQuotes = false;
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < str.length(); i++) {
        if (str.charAt(i) == '"') inQuotes = !inQuotes;
        else if (!inQuotes) sb.append(str.charAt(i));
    }
    System.out.println(sb.toString());
}