【问题标题】:Select a word on a phrase from string of Array Java从 Array Java 字符串中选择短语中的单词
【发布时间】:2021-05-29 01:03:20
【问题描述】:

输入短语: 从短语中取出一个单词并打印出来

输出:

我尝试过使用拆分,但它似乎不是这样工作的

但这是我的代码

public class Main  
{   
    public static void main(String args[])   
    {   
        
        String str              = "take a word out of the phrase and print it";  
        String[] stringarray    = str.split("take a word out of the phrase ",0);   
        String[] stringarray1   = str.split(" of the phrase and print it",0);
        String[] stringarray2   = str.split("of the",0);
        String[] stringarray3   = str.split("the",0);

        // This one doesn't work the way I wanted
        String[] stringarray4   = str.split("take a word out of  phrase and print it",0);
        
        for(int i=0; i<stringarray.length; i++)  
        {  
            System.out.println(stringarray[i]);  
        }
        for(int i=0; i<stringarray1.length; i++)  
        {  
            System.out.println(stringarray1[i]);  
        }
        for(int i=0; i<stringarray2.length; i++)  
        {  
            System.out.println(stringarray2[i]);  
        }
        for(int i=0; i<stringarray3.length; i++)  
        {  
            System.out.println(stringarray3[i]);  
        }
        for(int i=0; i<stringarray4.length; i++)  
        {  
            System.out.println(stringarray4[i]);  
        }
        
    }   
}  

下面是上面程序的输出

[1]and print it
[2]take a word out
[3]take a word out 
   phrase and print it
[4]take a word out of 
   phrase and print it
[5]take a word out of the phrase and print it
// I want "the" on the fifth output to be gone

【问题讨论】:

    标签: java string indexing split tokenize


    【解决方案1】:

    删除单词后构建一个新字符串

    1. 查找字符串索引
    2. 从索引复制到索引 + 长度
    
    String input = "take a word out of the phrase and print it";
    String target = "the";
    
    int start = input.indexOf(target);
    int finish = start + target.length;
    String output = input.substring(start, finish);
    
    

    【讨论】:

    • 长度不是字符串类的成员,而是一种方法,所以请更正int finish = start + target.length();
    【解决方案2】:

    您可以将字符串按空格分成两部分,然后像这样只打印第二部分

            String str   = "take a word out of the phrase and print it";  
            int numberOfWords = str.split(" ").length;
            String reducedPhrase = str;
             
            for(int i=0; i<numberOfWords-1; i++) {
                reducedPhrase = reducedPhrase.split(" ", 2)[1];
                System.out.println("reducedPhrase:"+ reducedPhrase);
            }
    

    【讨论】:

    • 请检查您的代码是否给出了数组索引超出范围的异常
    • @Ashish Mishra,我已经纠正了情况
    猜你喜欢
    • 2020-08-09
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    相关资源
    最近更新 更多