java - 在java中复制字符串中的前N个单词

标签 java string text words

我想选择文本字符串的前 N ​​个单词。 我尝试了 split()substring() 无济于事。 我想要的是选择以下祈祷文的前 3 个单词并将它们复制到另一个变量中。

例如,如果我有一个字符串:

String greeting = "Hello this is just an example"

我想将前 3 个单词放入变量 Z 中

Z = "Hello this is"

最佳答案

    String myString = "Copying first N numbers of words to a string";
    String [] arr = myString.split("\\s+"); 
         //Splits words & assign to the arr[]  ex : arr[0] -> Copying ,arr[1] -> first


        int N=3; // NUMBER OF WORDS THAT YOU NEED
        String nWords="";

        // concatenating number of words that you required
        for(int i=0; i<N ; i++){
             nWords = nWords + " " + arr[i] ;         
        }

    System.out.println(nWords);



注意:这里.split()函数返回一个字符串数组,该数组是通过围绕给定正则表达式的匹配项分割给定字符串计算得出的。

所以如果我编写如下代码

String myString = "1234M567M98723651";
String[] arr = myString.split("M"); //idea : split the words if 'M' presents

那么答案将是:
1234 和 567 存储到数组中。

这是通过将分割值存储到给定数组中来实现的。第一个分割值存储到 arr[0],第二个分割值存储到 arr[1]。

代码的后面部分用于连接所需数量的分割词

希望您能从中得到启发!!!
谢谢!

关于java - 在java中复制字符串中的前N个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29859698/

相关文章:

c# - 在C#中将字符串写入固定长度的字节数组

C# : delete repetitive character

c - 将西里尔符号保存在 C 中的 txt 文件中

ios - 如何在 Swift 上向数组添加文本前缀?

css - 文本在悬停时改变不透明度时闪烁

java - 如何在类中引用 EntityPlayer 方法

java - 为什么我的 .java 文件禁用错误检查?

Java generics unchecked cast - 可以在运行时检查吗?

java - 在方法体内抛出异常并在之后捕获它

c++ - 从可能引发异常的函数返回 std::string