【问题标题】:Trim a string to get second word, third word and fourth word in java? [duplicate]修剪一个字符串以获得java中的第二个单词,第三个单词和第四个单词? [复制]
【发布时间】:2014-10-24 16:14:48
【问题描述】:

我有两个字符串

一个是

String s1 = "我有 1000 美元";

其次是

String s2 = "我想要我的宠物";

我只需要在 s1 中获得“have”、“1000”、“dollars”。 同样,我只需要在 s2 中获取“want”、“my”和“pet”。

我知道如何使用代码获取“我”

String newS1 = s.substring(0, s.indexOf(" "));

有没有办法使用子字符串来实现这一点?

【问题讨论】:

  • @fooore 你真的需要使用子字符串吗?因为使用子字符串并不总是有效
  • 使用子字符串会更好,因为我看到关于人们使用 Patterns、.replaceAll() 等的线程。
  • String newS1 = s.substring(s.indexOf(" "), s.lastIndexOf(" ")); 不会像你说的那样做。 . .
  • @foooree 你的所有字符串都需要第二个和第三个单词吗?
  • 是的,我需要第二、三、四字

标签: java regex string


【解决方案1】:

如果您总是想在任何字符串中使用第二个、第三个和第四个单词,我建议您使用拆分函数。

代码:

    String s1 = "I have 1000 dollars";
    String[] sp = s1.split(" ");
    System.out.println("second word is " + sp[1]);
    System.out.println("third word is " + sp[2]);
    System.out.println("Fourth words is " +sp[3]);

输出:

second word is have
third word is 1000
fourth word is dollars

【讨论】:

    【解决方案2】:
    String trimFirstWord(String s) {
        return s.contains(" ") ? s.substring(s.indexOf(' ')).trim() : "";
    }
    

    【讨论】:

    • 他想要第二个和第三个词
    • 这将返回除第一个单词之外的所有单词——一旦 s.contains() 上的引号被更正——它不支持输入字符。此外,trim() 并不是真正需要的 - 将 s.indexOf(' ') 更改为 s.indexOf(' ') + 1 以删除第一个单词后的空格,但保留其余的前导和尾随空格。
    • 没问题。我可以处理这个。如果我可以删除第一个单词,那么我就可以使用 wordRemovedFirstSpace 并再次使用它。
    • 它甚至没有运行?!!!!!!线程“主”java.lang.RuntimeException 中的异常:无法编译的源代码 - 错误的符号类型:java.lang.String.contains
    • 这对我有用 String removeFirstSpace = s.contains(" ") 吗? s.substring(s.indexOf(" ")).trim() : "";
    【解决方案3】:

    您可以尝试以下 rgex 来获取第二、第三、第四个单词。

    ^\\S+\\s*(\\S+)\\s*(\\S+)\\s*(\\S+).*$
    

    DEMO

    组索引 1 包含第一个单词,索引 2 包含第二个单词,索引 3 包含第三个单词。

    Pattern regex = Pattern.compile("^\\S+\\s*(\\S+)\\s*(\\S+)\\s*(\\S+).*$");
     Matcher matcher = regex.matcher("I have 1000 dollars");
     while(matcher.find()){
            System.out.println(matcher.group(1));
            System.out.println(matcher.group(2));
            System.out.println(matcher.group(3));
    
    }
    

    输出:

    have
    1000
    dollars
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多