以下是我的代码:
String LongestWord(String a)
{
int lw=0;
int use;
String lon="";
while (!(a.isEmpty()))
{
a=a.trim();
use=a.indexOf(" ");
if (use<0)
{
break;
}
String cut=a.substring(0,use);
if(cut.length()>lw)
{
lon=cut;
}
lw=lon.length();
a=a.replace(cut," ");
}
return lon;
}
问题是,当我输入一个字符串时,"一个男孩在公园里玩"
它返回最长的单词"ying",因为当它第一次用"替换"cut"时,它也会删除所有的"a",这样它就变成了在循环的第一次迭代后,"男孩在公园里玩耍"
请弄清楚怎么了?
提前感谢!
您已经知道问题:程序进行了不需要的替换。
因此,停止更换。在这个程序中,被检查的单词被直接剪切,而不是使用有害的替换。
String LongestWord(String a)
{
int lw=0;
int use;
String lon="";
while (!(a.isEmpty()))
{
a=a.trim();
use=a.indexOf(" ");
if (use<0)
{
break;
}
String cut=a.substring(0,use);
if(cut.length()>lw)
{
lon=cut;
}
lw=lon.length();
a=a.substring(use+1); // cut the word instead of doing harmful replacement
}
return lon;
}
您可以使用split函数来获取字符串数组。
然后循环该数组以找到最长的字符串并返回。
String LongestWord(String a) {
String[] parts = a.split(" ");
String longest = null;
for (String part : parts) {
if (longest == null || longest.length() < part.length()) {
longest = part;
}
}
return longest;
}
我会使用数组:
String[] parts = a.split(" ");
然后你可以在各个部分上循环,对于每个元素(是一个字符串),你可以检查长度:
parts[i].length()
找到最长的一个。
我会用扫描仪来完成这个
String s = "the boy is playing in the parl";
int length = 0;
String word = "";
Scanner scan = new Scanner(s);
while(scan.hasNext()){
String temp = scan.next();
int tempLength = temp.length();
if(tempLength > length){
length = tempLength;
word = temp;
}
}
}
您检查每个单词的长度,如果它比以前的所有单词都长,则将该单词存储到字符串"word"
另一种方式使用Streams
。
Optional<String> max = Arrays.stream("a boy is playing in the park"
.split(" "))
.max((a, b) -> a.length() - b.length());
System.out.println("max = " + max);
如果您正在寻找不平凡的解决方案,您可以使用split
或map
在不使用的情况下解决它,但使用only one loop
static String longestWorld(String pharagragh) {
int maxLength = 0;
String word=null,longestWorld = null;
int startIndexOfWord = 0, endIndexOfWord;
int wordLength = 0;
for (int i = 0; i < pharagragh.length(); i++) {
if (pharagragh.charAt(i) == ' ') {
endIndexOfWord = i;
wordLength = endIndexOfWord - startIndexOfWord;
word = pharagragh.substring(startIndexOfWord, endIndexOfWord);
startIndexOfWord = endIndexOfWord + 1;
if (wordLength > maxLength) {
maxLength = wordLength;
longestWorld = word;
}
}
}
return longestWorld;
}
现在让我们测试一下
System.out.println(longestWorld("Hello Stack Overflow Welcome to Challenge World"));// output is Challenge
尝试:
package testlongestword;
/**
*
* @author XOR
*/
public class TestLongestWord{
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(LongestWord("a boy is playing in the park"));
}
public static String LongestWord(String str){
String[] words = str.split(" ");
int index = 0;
for(int i = 0; i < words.length; ++i){
final String current = words[i];
if(current.length() > words[index].length()){
index = i;
}
}
return words[index];
}
}