如何在Java中使用句子作为分隔符分割字符串?
String 类的 split() 方法接受一个表示分隔符的字符串值,并将其分割成一个标记(单词)数组,将两个分隔符之间出现的字符串视为一个标记。
例如,如果您将单个空格“ ”作为分隔符传递给此方法并尝试分割一个字符串。此方法将两个空格之间的单词视为一个标记,并返回当前字符串中单词(空格之间)的数组。
如果字符串不包含指定的分隔符,则此方法将返回一个包含整个字符串作为元素的数组。
示例
public class SplitExample { public static void main(String[] args) { String str = "Hi how are you welcome to Tutorialspoint"; String words[] = str.split(" "); for(String token : words) { System.out.println(token); } } }
输出
Hi how are you welcome to Tutorialspoint
使用句子作为分隔符分割字符串
如果您将句子作为分隔符传递,您也可以分割句子,如果这样做,则每次出现指定句子时,字符串都会被分割为一个单独的标记。
示例
以下 Java 程序将文件内容读入一个字符串,并使用带句子作为分隔符的 split() 方法将其分割。
public class StringOccurrence { public static String fileToString(String filePath){ Scanner sc = null; String input = null; StringBuffer sb = null; try { sc = new Scanner(new File(filePath)); sb = new StringBuffer(); while (sc.hasNextLine()) { input = sc.nextLine(); sb.append(" "+input); } } catch(Exception ex) { ex.toString(); } return sb.toString(); } public static void main(String args[]) throws FileNotFoundException { String filePath = "D://sampleData.txt"; String text = fileToString(filePath); String array[] = text.split("We don’t force our readers to sign up with us or submit their details either"); for(String token : array) { System.out.println(" "); System.out.println(token); } } }
输出
Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. The journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated, we worked our way to adding fresh tutorials to our repository which now proudly flaunts a wealth of tutorials and allied articles on topics ranging from programming languages to web designing to academics and much more. 40 million readers read 100 million pages every month. Our content and resources are freely available and we prefer to keep it that way to encourage our readers acquire as many skills as they would like to. No preconditions and no impediments. Simply Easy Learning!
广告