如何在Java中按句子将字符串分隔为定界符?
String类的split()方法接受表示定界符的String值,并拆分为标记(单词)数组,将出现两个定界符之间的字符串视为一个标记。
例如,如果将单个空格“”作为此方法的定界符,并尝试拆分String。此方法将两个空格之间的单词视为一个标记,并在当前String中返回一个单词数组(空格之间)。
如果String不包含指定的定界符,则此方法返回一个包含整个字符串作为元素的数组。
示例
public class SplitExample { public static void main(String[] args) { String str = "Hi how are you welcome to Nhooo"; String words[] = str.split(" "); for(String token : words) { System.out.println(token); } } }
输出结果
Hi how are you welcome to Nhooo
用句子分割字符串作为分隔符
如果每次指定的句子出现时,也可以通过传递一个句子作为定界符来分割一个句子,将字符串作为单独的标记进行划分。
示例
随后的Java程序将文件的内容读取到Sting中,并使用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); } } }
输出结果
nhooo.com 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!