java - 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;
}
}
解决方案
首先,您应该知道,==
使用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 "";
}
推荐阅读
- python - python - 如何在python中的.json文件中以给定格式从.csv文件中提取数据?
- google-analytics - 访问报告 API 的 Google 身份验证要求
- dynamics-crm - $batch 请求 - 与逐个执行的请求相比,它们是否提供客户端性能加速
- node.js - Firebase 生成圆形缩略图失败,代码为 1
- javascript - Jquery.Get 调用控制器方法并不总是有效
- algorithm - 魔方加密
- api - 当 precipType 为“rain”时,DarkSky 时间机器(历史)数据是否应显示 PrecipAccumulation
- postgresql - 我已经在 ubuntu 16.04 中安装了 Postgres 服务器 10.7,但我没有得到相同版本的 Postgres 客户端
- azure - 使用 Blob 存储触发器在 Azure 逻辑应用中禁用拆分功能时为空正文
- sql-server - 内存不足,无法完成此操作。请稍后再试,当excel中可能出现更多可用内存错误时