首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在java中对一个单词拆分字符串

在java中对一个单词拆分字符串
EN

Stack Overflow用户
提问于 2013-11-06 03:48:22
回答 2查看 280关注 0票数 2

对于“狗”,我如何区分一个字符串--“懒散狗跑得快”,这样我就得到了Strings ="The Lazy",“狗”,"is running“?在Java中

我使用的代码是字符串str=:“懒惰的狗像狗一样跑”;字符串dog=“狗”;String[] strArr= str.split(狗);for(int i=0;i )

它会返回:懒惰者运行起来就像

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-11-06 04:04:55

我建议使用正则表达式 (和分组)。正则表达式可以用来匹配几乎任何你想要的东西!

例如:

代码语言:javascript
复制
import java.util.regex.*;

public class PatternExample {

    public static void main(String[] args) {
        String split = "The Lazy dog is running fast";
        Pattern pattern = Pattern.compile("(.*)(dog)(.*)");
        Matcher matcher = pattern.matcher(split);
        while (matcher.find()) {
            for (int i = 0; i <= matcher.groupCount(); i++){
                System.out.println(i + "->" + matcher.group(i));
            }
        }
    }
}

给予:

代码语言:javascript
复制
0->The Lazy dog is running fast
1->The Lazy 
2->dog
3-> is running fast

采取2:无正则表达式

代码语言:javascript
复制
public class PatternExample {

    public static void main(String[] args) {
        String split = "The Lazy dog is running fast";
        String word = "dog";
        String tmp = split;
        while (tmp.contains(word)){
            int x = tmp.indexOf(word);
            System.out.println(tmp.substring(0,x));
            System.out.println(word);
            tmp = tmp.substring(x+word.length());
        }
        System.out.println(tmp);
    }
}
票数 1
EN

Stack Overflow用户

发布于 2013-11-06 04:05:51

我希望我正确地理解了你的问题,如果是这样的话,我将如何开始它,你仍然需要填补空白的边缘案例。您可以使用substringindexOf来代替split,但是不使用它似乎太方便了。

代码语言:javascript
复制
package test;


public class Main {
    public static void main(String[] args) {
        String sentence = "The Lazy dog is running fast";
        String word = "dog";
        String[] splitByWord = splitByWord(word, sentence);
        for (String string : splitByWord) {
            System.out.println(string);
        }

    }

    public static String[] splitByWord(String word, String sentence) {
        String[] split = sentence.split(" " + word + " ");
        //TODO: handle edge cases where word is not found in sentence, or first word, or last
        return new String[]{split[0], word, split[1]};
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19803733

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档