如何用java将字符串读到某个逗号
例如,我需要将文件读到某个逗号;如何用java将字符串读到某个逗号,java,string,file,Java,String,File,例如,我需要将文件读到某个逗号; String s=hii、lol、wow和,最后 需要输出为hii、lol、wow和 不希望最后一个逗号后跟字符 因为我的代码正在读取最后一个逗号字符串 示例:我正在将代码作为:最终 下面是我的代码 请引导我 File file =new File("C:/Users/xyz.txt"); FileInputStream inputStream = new FileInputStream(file); String filke = IOUtils.toStr
String s=hii、lol、wow和,最后
需要输出为hii、lol、wow和
不希望最后一个逗号后跟字符
因为我的代码正在读取最后一个逗号字符串
示例:我正在将代码作为:最终
下面是我的代码
请引导我
File file =new File("C:/Users/xyz.txt");
FileInputStream inputStream = new FileInputStream(file);
String filke = IOUtils.toString(inputStream);
String[] pieces = filke.split("(?=,)");
String answer = Arrays.stream(pieces).skip(pieces.length - 1).collect(Collectors.joining());
String www=answer.substring(1);
System.out.format("Answer = \"%s\"%n", www);
要使用stricly regex,可以使用
模式。compile
和Matcher
Pattern.compile("\w+(?=,)");
Matcher matcher = pattern.matcher(filke);
while (matcher.find()) {
System.out.println(matcher.group(1) + ","); // regex not good enough, maybe someone can edit it to include , (comma)
}
将匹配hii、lol、wow和,
请参见此处的正则表达式示例您不一定需要使用正则表达式来实现此目的。只需获取最后一个
,“
的索引,并获取从0
到该索引的子字符串:
String answer = "hii,lol,wow,and,finally";
String www = answer.substring(0, answer.lastIndexOf(','));
System.out.println(www); // prints hii,lol,wow,and
Java中的
String
有一个名为lastIndexOf(stringstr)
的方法。这可能对你有用。
假设您的输入是String s=“hii,lol,wow,and,finally”代码>
您可以执行String
操作,如:
String s = "hii,lol,wow,and,finally";
s = s.substring(0, s.lastIndexOf(","));
这将为您提供输出:hii、lol、wow和
如果您想使用Java8流为您做这件事,您可以尝试过滤器吗
String answer = Arrays.stream(pieces).filter(p -> !Objects.equals(p, pieces[pieces.length-1])).collect(Collectors.joining());
这将与您的销售代表一起打印Answer=“hii,lol,wow和”
。您应该知道问题。它必须是regex吗?为什么不删除最后的<代码>、<代码> +++ +一些子字符串,而LaxTimeXOF可能是你所需要的,所以使用SPLIT()来做,而忽略最后一个元素。@ String Hi,你能考虑一下谢谢吗?