是否有一种简单的方法来搜索可能包含Java中行分隔符的文本中的句子?

问题描述 投票:0回答:2

我有这个字符串

String text = "Hello world my " + System.lineSeparator() + "name is Bob";

我也有这句话

String sentence = "world my name is";

我注意到由于行分隔符,您无法在sentencetext中找到indexOf()。是否有简便快捷的方法仍可以通过多行字符串找到sentence

编辑:我还需要按原样打印找到的字符串,这意味着,如果在文本中找到System.lineSeparator()的地方有一个sentence,则需要使用该分隔符将其打印出来。

I / O的示例:

输入:

Hello world my
name is Bob

输出:

world my
name is

感谢您的所有答复!

java string indexof multiline separator
2个回答
1
投票

谢谢@alfasin

text.replaceAll(System.lineSeparator(), "").indexOf(sentence);

-2
投票

String.indexOf()似乎对我来说很好。这是一个示例。

https://repl.it/repls/ProperAcademicObject

示例中的代码如下:

String sentence = "Sentence";
String text = "This is a test." + System.lineSeparator() + "one two three." + System.lineSeparator() + sentence;

System.out.println(text);
System.out.println(text.indexOf("one two three"));
System.out.println(text.indexOf(sentence));

输出如下:

This is a test.
one two three.
Sentence
16
31
© www.soinside.com 2019 - 2024. All rights reserved.