在java中复制字符串中的前N个单词 [英] Copy the first N words in a string in java

查看:30
本文介绍了在java中复制字符串中的前N个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to select the first N words of a text string. I have tried split() and substring() to no avail. What I want is to select the first 3 words of the following prayer and copy them to another variable.

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

For example if I have a string:

String greeting = "Hello this is just an example"

我想进入变量 Z 的前 3 个词,以便

I want to get into the variable Z the first 3 words so that

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() 函数返回一个字符串数组,该字符串通过围绕给定正则表达式的匹配项

NOTE : Here .split() function returns an array of strings computed by splitting a given string around matches of the given regular expression

所以如果我写如下代码

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

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

then answers will be :
1234 and 567 where stored into an array.

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

This is doing by storing the split values into the given array. first split value store to arr[0], second goes to arr[1].

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

Later part of the code is for concatenating the required number of split words

希望你能从中得到一个想法!!!
谢谢!

Hope that you can get an idea from this!!!
Thank you!

这篇关于在java中复制字符串中的前N个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆