首页 > 解决方案 > how to return a word from a string

问题描述

I apologize for the messy code, but these are two methods are ones we are supposed to use. I have to find the word end in a given string, if there is no end in the string return an empty string. ex (the, end said the author) 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;
    }
}

标签: javaarraysstringif-statementreturn-type

解决方案


首先,您应该知道,==使用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 "";
}

推荐阅读