栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从Java中的另一个字符串中删除字符串

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从Java中的另一个字符串中删除字符串

这是不使用正则表达式的解决方案。我认为它不如我的其他答案,因为它更长且不清楚,但是如果性能确实非常重要,那么这就是 O(n) ,其中 n
是文本的长度。

Set<String> stopWords = new HashSet<String>();stopWords.add("a");stopWords.add("and");// and so on ...String sampleText = "I would like to do a nice novel about nature AND people";StringBuffer clean = new StringBuffer();int index = 0;while (index < sampleText.length) {  // the only word delimiter supported is space, if you want other  // delimiters you have to do a series of indexOf calls and see which  // one gives the smallest index, or use regex  int nextIndex = sampleText.indexOf(" ", index);  if (nextIndex == -1) {    nextIndex = sampleText.length - 1;  }  String word = sampleText.substring(index, nextIndex);  if (!stopWords.contains(word.toLowerCase())) {    clean.append(word);    if (nextIndex < sampleText.length) {      // this adds the word delimiter, e.g. the following space      clean.append(sampleText.substring(nextIndex, nextIndex + 1));     }  }  index = nextIndex + 1;}System.out.println("Stop words removed: " + clean.toString());


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/463802.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号