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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29000193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:31:46  来源:igfitidea点击:

return the first word in any string (Java)

javastring

提问by alok

I have to be able to input any two words as a string. Invoke a method that takes that string and returns the first word. Lastly display that word.

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

The method has to be a for loop method. 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 循环方法。我有点知道如何使用子字符串,并且我知道如何通过使用 .substring(0,x) x 来返回第一个单词,即第一个单词的长度。

How can I make it so that no matter what phrase I use for the string, it will always return the first word? And please explain what you do, because this is my first year in a CS class. Thank you!

我怎样才能做到无论我对字符串使用什么短语,它都将始终返回第一个单词?请解释你的工作,因为这是我在 CS 课程的第一年。谢谢!

回答by candied_orange

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

我必须能够输入任意两个单词作为字符串

The zero, one, infinity design rulesays there is no such thing as two. Lets design it to work with any number of words.

零、一、无穷大设计规则说没有二这样的东西。让我们设计它以处理任意数量的单词。

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

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

然后调用并显示从方法返回的第一个单词,

So we need a method that takes a String and returns a String.

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

// 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
}

staticlets us call it from main without needing to create instances of anything. publiclets us call it from another class if we want.

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

.split(" ")creates an array of Strings delimited at every space. [0]indexes into that array and gives the first word since arrays in java are zero indexed (they start counting at 0).

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

and the method has to be a for loop method

并且该方法必须是 for 循环方法

Ah crap, then we have to do it the hard way.

啊,废话,那我们就得硬着头皮去做。

// 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.

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

There it is, using those methods you mentioned and the for loop. What more could you want?

就是这样,使用您提到的那些方法和 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?

但是我怎样才能做到无论我对字符串使用什么短语,它总是会返回第一个单词?

Man you're picky :) OK fine:

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

// 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; 
}

Put it all together it looks like this:

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

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; 
    }    
}

And it prints this:

它打印了这个:

One

Hey wait, you changed the firstWord method there.

嘿等等,你在那里改变了 firstWord 方法。

Yeah I did. This style avoids the need for a result string. Multiple returns are frowned on by old programmers that never got used to garbage collected languages or using finally. They want one place to clean up their resources but this is java so we don't care. Which style you should use depends on your instructor.

是啊,我做了。这种风格避免了对结果字符串的需要。从未习惯垃圾收集语言或使用finally. 他们想要一个地方来清理他们的资源,但这是 Java,所以我们不在乎。你应该使用哪种风格取决于你的导师。

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

请解释你的工作,因为这是我在 CS 课程的第一年。谢谢!

What do I do? I post awesome! :)

我该怎么办?我发的真棒!:)

Hope it helps.

希望能帮助到你。

回答by Anthony Dito

String line = "Hello my name is...";
int spaceIndex = line.indexOf(" ");
String firstWord = line.subString(0, spaceIndex);

So, you can think of line as an array of chars. Therefore, line.indexOf(" ") gets the index of the space in the line variable. Then, the substring part uses that information to get all of the characters leading up to spaceIndex. So, if space index is 5, it will the substring method will return the indexes of 0,1,2,3,4. This is therefore going to return your first word.

因此,您可以将 line 视为字符数组。因此, line.indexOf(" ") 获取 line 变量中空格的索引。然后,子字符串部分使用该信息来获取导致 spaceIndex 的所有字符。因此,如果空间索引为 5,则 substring 方法将返回 0、1、2、3、4 的索引。因此,这将返回您的第一个单词。

回答by Jean-Fran?ois Savard

Since you did not specify the order and what you consider as a word, I'll assume that you want to check in given sentence, until the first space.

由于您没有指定顺序和您认为的单词,我假设您想检查给定的句子,直到第一个空格。

Simply do

简单地做

int indexOfSpace = sentence.indexOf(" ");
firstWord = indexOfSpace == -1 ? sentence : sentence.substring(0, indexOfSpace);

Note that this will give an IndexOutOfBoundExceptionif there is no space in the sentence.

请注意,IndexOutOfBoundException如果句子中没有空格,这将给出一个。

An alternative would be

另一种选择是

String sentences[] = sentence.split(" ");
String firstWord = sentence[0];

Of if you really need a loop,

如果你真的需要一个循环,

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

回答by mk.

The first word is probably the substring that comes before the first space. So write:

第一个单词可能是第一个空格之前的子字符串。所以写:

int x = input.indexOf(" ");

But what if there is no space? xwill be equal to -1, so you'll need to adjust it to the very end of the input:

但是如果没有空间怎么办?x将等于 -1,因此您需要将其调整到输入的最后:

if (x==-1) { x = input.length(); }

Then use that in your substring method, just as you were planning. Now you just have to handle the case where inputis the blank string "", since there is no first word in that case.

然后在您的子字符串方法中使用它,就像您计划的那样。现在您只需要处理 where inputis the blank string 的情况"",因为在这种情况下没有第一个单词。

回答by Kizivat

You may get the position of the 'space' character in the input string using String.indexOf(String str)which returns the index of the first occurrence of the string in passed to the method.

您可以获得输入字符串中“空格”字符的位置,使用String.indexOf(String str)它返回传递给方法的字符串第一次出现的索引。

E.g.:

例如:

int spaceIndex = input.indexOf(" ");
String firstWord = input.substring(0, spaceIndex);

回答by Kizivat

Maybe this can help you figure out the solution to your problem. Most users on this site don't like doing homework for students, before you ask a question, make sure to go over your ISC book examples. They're really helpful.

也许这可以帮助您找出问题的解决方案。该网站上的大多数用户不喜欢为学生做作业,在您提出问题之前,请务必查看您的 ISC 书籍示例。他们真的很有帮助。

String Str = new String("Welcome to Stackoverflow");

System.out.print("Return Value :" );
System.out.println(Str.substring(5) );

System.out.print("Return Value :" );
System.out.println(Str.substring(5, 10) );