First word in string java

None of these answers appears to define what the OP might mean by a «word». As others have already said, a «word boundary» may be a comma, and certainly can’t be counted on to be a space, or even «white space» (i.e. also tabs, newlines, etc.)

At the simplest, I’d say the word has to consist of any Unicode letters, and any digits. Even this may not be right: a String may not qualify as a word if it contains numbers, or starts with a number. Furthermore, what about hyphens, or apostrophes, of which there are presumably several variants in the whole of Unicode? All sorts of discussions of this kind and many others will apply not just to English but to all other languages, including non-human language, scientific notation, etc. It’s a big topic.

But a start might be this (NB written in Groovy):

String givenString = "one two9 thr0ee four"
// String givenString = "oňňÜÐæne;:tŵo9===tĥr0eè? four!"
// String givenString = "mouse"
// String givenString = "&&^^^%"

String[] substrings = givenString.split( '[^\p{L}^\d]+' )

println "substrings |$substrings|"

println "first word |${substrings[0]}|"

This works OK for the first, second and third givenStrings. For «&&^^^%» it says that the first «word» is a zero-length string, and the second is «^^^». Actually a leading zero-length token is String.split‘s way of saying «your given String starts not with a token but a delimiter».

NB in regex p{L} means «any Unicode letter». The parameter of String.split is of course what defines the «delimiter pattern»… i.e. a clump of characters which separates tokens.

NB2 Performance issues are irrelevant for a discussion like this, and almost certainly for all contexts.

NB3 My first port of call was Apache Commons’ StringUtils package. They are likely to have the most effective and best engineered solutions for this sort of thing. But nothing jumped out… https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html … although something of use may be lurking there.

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

The zero, one, infinity design rule says 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
}

static lets us call it from main without needing to create instances of anything. public lets us call it from another class if we want.

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

and the method has to be a for loop method

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.

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

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.

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.

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

What do I do? I post awesome! :)

Hope it helps.

11 ответов

Второй параметр метода split является необязательным, и если задано, будет разделяться только целевая строка N раз.

Например:

String mystring = "the quick brown fox";
String arr[] = mystring.split(" ", 2);

String firstWord = arr[0];   //the
String theRest = arr[1];     //quick brown fox

В качестве альтернативы вы можете использовать метод substring String.

Johan Sjöberg
21 фев. 2011, в 16:47

Поделиться

Вы должны делать это

String input = "hello world, this is a line of text";

int i = input.indexOf(' ');
String word = input.substring(0, i);
String rest = input.substring(i);

Вышеупомянутый — самый быстрый способ выполнить эту задачу.

adarshr
21 фев. 2011, в 16:43

Поделиться

Чтобы упростить вышеизложенное:

text.substring(0, text.indexOf(' ')); 

Вот готовая функция:

  private String getFirstWord(String text) {
    int index = text.indexOf(' ');
    if (index > -1) { // Check if there is more than one word.
      return text.substring(0, index); // Extract first word.
    } else {
      return text; // Text is the first word itself.
    }
  }

Zon
09 июнь 2013, в 09:52

Поделиться

Простой, который я использовал, это

str.contains(" ") ? str.split(" ")[0] : str

Где str — ваша строка или текст bla bla:). Итак, , если

  • str имеет пустое значение, которое оно возвращает, как оно есть.
  • str имеет одно слово, оно возвращается как есть.
  • str — несколько слов, он извлекает первое слово и возвращает.

Надеюсь, что это будет полезно.

Madan Sapkota
02 июль 2015, в 17:51

Поделиться

Вы можете использовать String.split с лимитом 2.

    String s = "Hello World, I'm the rest.";
    String[] result = s.split(" ", 2);
    String first = result[0];
    String rest = result[1];
    System.out.println("First: " + first);
    System.out.println("Rest: " + rest);

    // prints =>
    // First: Hello
    // Rest: World, I'm the rest.
  • API docs для: split

miku
21 фев. 2011, в 16:08

Поделиться

Lucas Zamboulis
21 фев. 2011, в 17:26

Поделиться

Вы можете использовать сканер

http://download.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

Сканер также может использовать разделители кроме пробелов. Этот пример читает несколько строк из строки:

     String input = "1 fish 2 fish red fish blue fish";
     Scanner s = new Scanner(input).useDelimiter("\s*fish\s*");
     System.out.println(s.nextInt());
     System.out.println(s.nextInt());
     System.out.println(s.next());
     System.out.println(s.next());
     s.close(); 

выводит следующий результат:

     1
     2
     red
     blue

PDStat
21 фев. 2011, в 17:11

Поделиться

import org.apache.commons.lang3.StringUtils;

...
StringUtils.substringBefore("Grigory Kislin", " ")

GKislin
11 фев. 2016, в 17:37

Поделиться

Я знаю, что на этот вопрос уже был дан ответ, но у меня есть другое решение (для тех, кто все еще ищет ответы), которые могут вписываться в одну строку: он использует функциональность split, но дает только 1-ю сущность.

String test = "123_456";
String value = test.split("_")[0];
System.out.println(value);

На выходе будет показано:

123

Hughsie28
06 фев. 2018, в 13:35

Поделиться

вот так:

final String str = "This is a long sentence";
final String[] arr = str.split(" ", 2);
System.out.println(Arrays.toString(arr));

arr[0] — первое слово, arr[1] — это остальное

Sean Patrick Floyd
21 фев. 2011, в 17:35

Поделиться

String anotherPalindrome = "Niagara. O roar again!"; 
String roar = anotherPalindrome.substring(11, 15); 

Вы также можете сделать это

surabhi kale
23 нояб. 2012, в 20:42

Поделиться

Ещё вопросы

  • 1Каково максимальное значение силы сигнала спутника?
  • 0Javascript — ошибка в обработчике событий
  • 1Разница в формате PIP
  • 0Шаблоны Jquery — вложенный JSON
  • 0Как выделить совпадающее слово в автозаполнении jquery ui
  • 0Установить флажки в JQuery
  • 1Какие различия между компаратором и сопоставимым? [Дубликат]
  • 0Указатель на указатель оболочки C ++ / CLI
  • 1Как заменить всю строку во всех столбцах, используя панд?
  • 0Игнорирование определенной записи во время выполнения в MySQL
  • 1NHibernate: Делать сессионный синглтон плохой практикой?
  • 1Удалить одну метку секции пирога из JFreeChart
  • 0memcpy ведет себя неожиданно
  • 1Как автоматически реализовано свойство Get возвращает определенный элемент данных
  • 1Соединение SoapUI JDBC с Apache Cassandra
  • 0node и knex — заполнение промежуточной таблицы проблем Promise
  • 0SQL вычитание столбца из 2 других столбцов?
  • 1Как мы оцениваем строку постфикса с унарным оператором?
  • 1Взаимодействие с файлами, которые имеют символы Юникода в именах файлов / escape-последовательности
  • 0Сборка PhoneGap — Config.XML — Сбой REST CALL из-за ошибки ConnectionError
  • 0C ++ Изменение свойств из базового класса
  • 0Использование $ routeParams внутри фильтра повторов
  • 0Cocos2D-x Включить CCMenuItemSprite по тегу c ++
  • 1Возврат объектов из массива с использованием операции вложенной карты
  • 1C # несколько Contentpresenter на кнопку стиля (Windows 8.1)
  • 0PHP Войти — несколько условий IF не работают
  • 0как сдвинуть div в верхнем / левом / правом / нижнем направлении по клику
  • 0MySQL: пустая строка с подстановочными знаками не возвращает никаких результатов
  • 1OnInvitationReceivedListener не срабатывает надежно (если вообще работает) — Clicker кнопки Google Play Services
  • 0Установка MySQL конфликтует с MySQL-сервером
  • 1Как я должен вызвать экземпляр, который реализует абстрактный метод [duplicate]
  • 1R эквивалент Python’s Dask
  • 0Чтение и запись текстур в HLSL 5.0 (отложенное затенение)
  • 0Рецепты для внедрения сложных структур в разборный заголовок в jQuery Mobile
  • 1Почему связыватель модели смешивает поля идентификаторов?
  • 1sql получить номер, диапазон которого является другим числом
  • 1Как установить charset = «utf-8» в самом файле javascript
  • 1android strings.xml на разных языках, сценарий
  • 1Android GRef увеличивается при установке тега просмотра
  • 0Данные шейдера как массив символов — ошибка 0xFEEEFEEE
  • 1Pandas Series.rename не отражено в столбцах DataFrame
  • 1Tabris.js XMLHttpRequests не принимает ответы: готовность 1
  • 0статический заголовок внутри прокручиваемого div
  • 1Запись данных в сетке в текстовый файл с форматированием
  • 1Как получить данные с Max Date в linq
  • 0Как я могу предотвратить подачу заявки $ уже в этом деле?
  • 0Получить все разговоры от одного пользователя в разных чатах
  • 1Таймер остановки в событии onDisconnect ()
  • 0Как изменить фон сайта в зависимости от размера окна браузера?
  • 1Панды — сумма отдельных кадров с ежемесячными столбцами

None of these answers appears to define what the OP might mean by a «word». As others have already said, a «word boundary» may be a comma, and certainly can’t be counted on to be a space, or even «white space» (i.e. also tabs, newlines, etc.)

At the simplest, I’d say the word has to consist of any Unicode letters, and any digits. Even this may not be right: a String may not qualify as a word if it contains numbers, or starts with a number. Furthermore, what about hyphens, or apostrophes, of which there are presumably several variants in the whole of Unicode? All sorts of discussions of this kind and many others will apply not just to English but to all other languages, including non-human language, scientific notation, etc. It’s a big topic.

But a start might be this (NB written in Groovy):

String givenString = "one two9 thr0ee four"
// String givenString = "oňňÜÐæne;:tŵo9===tĥr0eè? four!"
// String givenString = "mouse"
// String givenString = "&&^^^%"

String[] substrings = givenString.split( '[^\p{L}^\d]+' )

println "substrings |$substrings|"

println "first word |${substrings[0]}|"

This works OK for the first, second and third givenStrings. For «&&^^^%» it says that the first «word» is a zero-length string, and the second is «^^^». Actually a leading zero-length token is String.split‘s way of saying «your given String starts not with a token but a delimiter».

NB in regex p{L} means «any Unicode letter». The parameter of String.split is of course what defines the «delimiter pattern»… i.e. a clump of characters which separates tokens.

NB2 Performance issues are irrelevant for a discussion like this, and almost certainly for all contexts.

NB3 My first port of call was Apache Commons’ StringUtils package. They are likely to have the most effective and best engineered solutions for this sort of thing. But nothing jumped out… https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html … although something of use may be lurking there.

I have Strings like these:

"xyz abc(15 yr)"
"xyz(15 yr)"

Remember xyz(first word) is not a fix length ,it may be more than three or less

In both string I want to extract only «xyz».How to do this task and store in a single string.


W represents any non-word character and .split splits the string into a string array wherever W is found. [0] returns the first element in the array.

String firstWord = line.split("\W")[0];

Check out this table. This is where I found the proper regex expression.

https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

Понравилась статья? Поделить с друзьями:
  • First word in css
  • First word he said
  • First word from string php
  • First word from jesus
  • First word for kids