Java 如何从字符串中返回单词
我为混乱的代码道歉,但这是我们应该使用的两种方法。我必须在给定字符串中找到单词Java 如何从字符串中返回单词,java,arrays,string,if-statement,return-type,Java,Arrays,String,If Statement,Return Type,我为混乱的代码道歉,但这是我们应该使用的两种方法。我必须在给定字符串中找到单词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 *
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;
}
}
公共类结束{
/**
*找到单词end的第一个外观。
*将字符串返回到单词末尾
*如果单词end不存在,则返回空字符串
*/
公共静态int-endArray(字符串[]个字){
int end=0;
for(int i=0;i
首先,您应该知道,将字符串与=
进行比较是不正确的,请改用equals
方法:
if(“end”.equals(单词[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 "";
}
公共静态字符串结尾(字符串[]个字){
String allStrings=“”;//实际上,最好使用StringBuilder,但对于您的目标来说,字符串浓缩就足够了
for(int i=0;i
请尝试以下代码:
import java.util.*;
公共班机
{
公共字符串getSortedGrades(字符串[]arg){
字符串newStr=“”;
对于(int i=0;我非常感谢您,您提供的以下代码是否与我的输出匹配?例如,像(作者说的end)ouput=(“end”)这样的字符串,该方法返回end之前的所有内容,因此如果您需要在返回的字符串中包含单词end
,它应该看起来像returnallstrings+“end”
。第二件事是如何从字符串中获取数组。因此,如果您这样做:“结尾说作者”。拆分(“”
),则输出字符串(加上我之前的更改)将是结尾(请注意,没有空格,并且有逗号,因为它在字符串中)。第三,在输入字符串中“结尾说作者”包含小写字母“e”的end
,但你希望“end”是大写的。这不是它的工作原理。我不明白为什么给定字符串(结尾说作者)
的输出是结尾
。你是如何将字符串拆分成字符串数组的?
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);
}
}