【问题标题】:how to return a word from a string如何从字符串中返回一个单词
【发布时间】:2019-11-14 18:07:34
【问题描述】:

我为混乱的代码道歉,但这是我们应该使用的两种方法。我必须在给定的字符串中找到单词end,如果字符串中没有结尾,则返回一个空字符串。 ex (the, end 表示作者) output= the end

public class end {

    /**
    * find first apperance of the word end.
     * return the string up to word end
     * return empty string if the word end isn't there 
     */

    public static int endArray(String[] words) {
        int end = 0;
        for (int i = 0; i < words.length; i ++) {
            end ++;
            if (words[i] == "end") {
                end++;
            } else {
                end = -1;
            }
        }
    }

    public static String end(String[] words) {
        String end = "-1";
        for (int i = 0; i < words.length; i ++) {
            end+= words[i];
            if (words[i] == "end") {
                System.out.println(words[i-1]);
                end++;
            }

        }    
        return end;
    }
}

【问题讨论】:

  • 我无法弄清楚为什么给定字符串(the, end said the author) 的输出是the end。你是怎么把字符串拆分成字符串数组的?

标签: java arrays string if-statement return-type


【解决方案1】:

首先,您应该知道,将字符串与== 进行比较是不正确的,请改用equals 方法: if ("end".equals(words[1])) { ...

我会这样实现它:

public static String end(String[] words) {
    String allStrings = ""; // actually, it'd be better to use StringBuilder, but for your goal string concatination is enough
    for (int i = 0; i < words.length; i++) {
        if ("end".equals(words[i])) {
            return allStrings;
        }
        allStrings += words[i]; // maybe here we should add spaces ?
    }
    // the word 'end' hasn't been found, so return an empty string
    return "";
}

【讨论】:

  • 非常感谢,您提供的以下代码是否与我的输出匹配?例如像 (The, end 表示作者)这样的字符串 ouput = ("The End")
  • 该方法返回之前结束的所有内容,因此如果您需要在返回的字符串中包含单词end,它应该看起来像return allStrings + "end"。第二件事是如何从字符串中获取数组。因此,如果您执行以下操作:"The, end said the author".split(" "),那么输出字符串(以及我之前的更改)将是 The,end(注意没有空格,并且有一个逗号,因为它在您的字符串中)。第三,在输入字符串“The, end said the author”中包含end,字母“e”小写,但您希望“End”大写。这不是它的工作原理。
【解决方案2】:

试试这个代码:

import java.util.*;
public class Main
{
    public  String getSortedGrades(String[] arg){
    String newStr = "";
    for(int i=0; i<arg.length; i++){
        if(arg[i]=="end"){
            newStr+=arg[i];
            return newStr;
        }else{
            newStr+=arg[i]+" ";
        }
    }
    return newStr.contains("end")?newStr: " " ;
}
    public static void main(String []args){
        System.out.println("Hello World");
        Main m =new Main();
        String[] input ={"the", "end", "said", "the", "author"}; 
       String s =  m.getSortedGrades(input);
       System.out.println(s);
    }
}

【讨论】:

    猜你喜欢
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 2017-10-29
    • 2014-01-19
    • 2020-06-06
    相关资源
    最近更新 更多