gpt4 book ai didi

java - 返回任何字符串中的第一个单词 (Java)

转载 作者:行者123 更新时间:2023-12-01 06:30:34 25 4
gpt4 key购买 nike

我必须能够输入任意两个单词作为字符串。调用一个接受该字符串并返回第一个单词的方法。最后显示该单词。

该方法必须是for 循环方法。我有点知道如何使用子字符串,并且我知道如何通过使用 .substring(0,x) x 来返回第一个单词,即第一个单词的长度。

如何才能使无论我对字符串使用什么短语,它总是返回第一个单词?请解释一下你的工作,因为这是我第一年参加计算机科学类(class)。谢谢!

最佳答案

I have to be able to input any two words as a string

The zero, one, infinity design rule说没有两个这样的东西。让我们将其设计为可处理任意数量的单词。

String words = "One two many lots"; // This will be our input

and then invoke and display the first word returned from the method,

所以我们需要一个接受字符串并返回字符串的方法。

// Method that returns the first word
public static String firstWord(String input) {
return input.split(" ")[0]; // Create array of words and return the 0th word
}

static 让我们可以从 main 调用它,而无需创建任何实例。如果需要,public 让我们可以从另一个类中调用它。

.split("") 创建一个以空格分隔的字符串数组。[0] 对该数组进行索引并给出第一个单词,因为 java 中的数组是零索引的(它们从 0 开始计数)。

and the method has to be a for loop method

啊糟糕,那我们就得用困难的方式来做。

// Method that returns the first word
public static String firstWord(String input) {
String result = ""; // Return empty string if no space found

for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break; // because we're done
}
}

return result;
}

I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.

就是这样,使用您提到的那些方法和 for 循环。您还想要什么?

But how can I make it so that no matter what phrase I use for the string, it will always return the first word?

伙计,你很挑剔:)好吧:

// Method that returns the first word
public static String firstWord(String input) {
String result = input; // if no space found later, input is the first word

for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break;
}
}

return result;
}

把它们放在一起看起来像这样:

public class FirstWord {

public static void main(String[] args) throws Exception
{
String words = "One two many lots"; // This will be our input
System.out.println(firstWord(words));
}

// Method that returns the first word
public static String firstWord(String input) {

for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
return input.substring(0, i);
}
}

return input;
}
}

它打印出这个:

One

Hey wait, you changed the firstWord method there.

是的,我做到了。这种风格避免了对结果字符串的需要。多次返回对于那些从未习惯垃圾收集语言或使用finally的老程序员来说是不受欢迎的。他们想要一个地方来清理他们的资源,但这是java,所以我们不在乎。您应该使用哪种风格取决于您的教练。

And please explain what you do, because this is my first year in a CS class. Thank you!

我该怎么办?我发帖太棒了! :)

希望有帮助。

关于java - 返回任何字符串中的第一个单词 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29000193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com