Get last word from string

we have that string:

"I like to eat apple"

How can I obtain the result "apple" ?

Félix Adriyel Gagnon-Grenier's user avatar

asked Jun 14, 2012 at 8:35

Oscar's user avatar

0

// Your string
$str = "I like to eat apple";
// Split it into pieces, with the delimiter being a space. This creates an array.
$split = explode(" ", $str);
// Get the last value in the array.
// count($split) returns the total amount of values.
// Use -1 to get the index.
echo $split[count($split)-1];

answered Jun 14, 2012 at 8:36

Rick Kuipers's user avatar

Rick KuipersRick Kuipers

6,5962 gold badges17 silver badges37 bronze badges

2

$str = 'I like to eat apple';
echo substr($str, strrpos($str, ' ') + 1); // apple

answered Jun 14, 2012 at 8:37

flowfree's user avatar

flowfreeflowfree

16.2k12 gold badges51 silver badges76 bronze badges

Try:

$str = "I like to eat apple";
end((explode(" ",$str));

kenorb's user avatar

kenorb

152k85 gold badges670 silver badges732 bronze badges

answered Jan 9, 2014 at 20:48

m4rtijn's user avatar

1

Try this:

$array = explode(' ',$sentence);
$last = $array[count($array)-1];

Will Vousden's user avatar

Will Vousden

32.2k9 gold badges84 silver badges94 bronze badges

answered Jun 14, 2012 at 8:37

Milan Halada's user avatar

Milan HaladaMilan Halada

1,93318 silver badges28 bronze badges

0

Get last word of string

$string =»I like to eat apple»;
$las_word_start = strrpos($string, ‘ ‘) + 1; // +1 so we don’t include the space in our result
$last_word = substr($string, $last_word_start);
echo $last_word // last word : apple

answered May 31, 2017 at 6:23

Reena Mori's user avatar

Reena MoriReena Mori

6476 silver badges15 bronze badges

1

How about this get last words or simple get last word from string just by passing the amount of words you need get_last_words(1, $str);

public function get_last_words($amount, $string)
{
    $amount+=1;
    $string_array = explode(' ', $string);
    $totalwords= str_word_count($string, 1, 'àáãç3');
    if($totalwords > $amount){
        $words= implode(' ',array_slice($string_array, count($string_array) - $amount));
    }else{
        $words= implode(' ',array_slice($string_array, count($string_array) - $totalwords));
    }

    return $words;
}
$str = 'I like to eat apple';
echo get_last_words(1,  $str);

answered Dec 25, 2013 at 12:33

M Khalid Junaid's user avatar

M Khalid JunaidM Khalid Junaid

63.6k10 gold badges90 silver badges117 bronze badges

<?php
// your string
$str = 'I like to eat apple';

// used end in explode, for getting last word
$str_explode=end(explode("|",$str));
echo    $str_explode;

?>

Output will be apple.

Jeffrey Bosboom's user avatar

answered Mar 2, 2015 at 3:04

Talha Mughal's user avatar

In this tutorial, I’ll discuss how you can get the last word from a given string in Python. It’s very easy to get the last word from a given string in Python. To get the last word from a string, we have to convert the string into a list at the first. After converting the string into a list, simply we can use the slicing operator to get the last word of the string and then we can print it. For converting a string into a list we can simply use the split() method.

Syntax:

your_string.split(Separator, Maxsplit)

Separator: This is optional. This is used to specify where we want to split the string. By default, it takes whitespace as a separator.

Maxsplit : This is also optional. This is used to specify how many splits we want to do in the given string. By default, it takes the value as -1, which means all the occurrences or no limit on the number of splits.

Now, let me give an example to understand the concept

#taking input from the user
string = input("Enter your string: ")

#splitting the string
words = string.split()

#slicing the list (negative index means index from the end)
#-1 means the last element of the list
print(words[-1])

Run this code online

Output :

Enter your string: Welcome to Codespeedy
Codespeedy

In this above code, I gave the input as ‘Welcome to Codespeedy’ and it gave me output as ‘Codespeedy’ that is the last word of the string.

So I hope now you’re familiar with the concept of how you can get the last word from a string.

Also read:

  • Python string rjust() and ljust() methods

Java get last word in string

1. Overview

In this article, we will learn the various ways to get the last word of a Java String.

2. Use String#substring method to get the last word

The substring() method of the java String class returns a part of the string. You can use the below overloaded substring method to get the last word of a Java string.

public String substring(int startIndex)

Now, we know the method to get a part of the string. But how to find the startIndex of the last word of a string.

You must look for the index of the last space character in the string and next to it would be your last word. To do this, use the lastIndexOf method.

pubic int lastIndexOf(int ch)

Let’s take the below code. The index of space is 26 and last word sentence starts from 27th index.

public class Main {
    public static void main(String args[]) {
        String lastWordStr =  "Find the last word in this sentence".trim();

        String lastWord = lastWordStr.substring(lastWordStr.lastIndexOf(" ")+1);
        System.out.println(lastWord); /* prints sentence */
    }
}

The above code would work correctly even if the string contains only one word. For example, the below lastWordStr has only a single word sentence. Still, this substring expression would return the sentence correctly.

Here, the lastIndexOf returns -1 as there is no space found in the string and next index to -1 is 0. So, the substring method takes the string from index 0 and returns it.

public static void main(String args[]) {
        String lastWordStr =  "sentence";
        String lastWord = lastWordStr.substring(lastWordStr.lastIndexOf(" ")+1); /* lastIndexOf returns -1, so -1+1 = 0 index */
        System.out.println(lastWord); /* prints sentence */
    }

2.2. Use String#split method to get string last word

You can use split method of the String class to split the string using the space delimiter into array of words.

In the below code, we have split the lastWordStr by using the space. So parts array would have the elements “Last”, “word”, “in”, “a”, “sentence”. Now, we get the last element or word "sentence" from the array using its index.

public static void main(String args[]) {
        String lastWordStr = "Last word in a sentence";
        String[] parts = lastWordStr.split(" ");
        String lastWord = parts[parts.length - 1];
        System.out.println(lastWord); /* prints sentence */
    }

2.3. Use String#replaceAll method to get the last word of a string

You can use replaceAll method of String to get the last word of the string.

In the below code, replaceAll regex match the entire string from ^ (start) to $ (end). Then, captures the last sequence of w+ in a capturing group 1 (captures the last word sentence), and replaces the entire string using $1 (capturing group).

 public static void main(String args[]) {
        String lastWordStr = "Last word in a sentence";
        String lastWord = lastWordStr.replaceAll("^.*?(\w+)\W*$", "$1");
        System.out.println(lastWord); /* prints sentence */
    }
  • .*? matches as few characters possible (except for line terminators)
  •  1st Capturing Group (w+)w matches any word character ([a-zA-Z0-9_])+ as many times possible
  • W matches any non-word character ([^a-zA-Z0-9_])* as many times as possible

2.4. Use StringUtils#substringAfterLast apache commons

You can use substringAfterLast method of StringUtils class that is available in apache commons library. To use it, you must add the apache commons dependency in your project.

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.11</version>
</dependency>

In the below code, we are checking if the string has only a single word or not. If there are more words, then we invoke the substringAfterLast by passing the space as an argument to separate the last word.

public static void main(String args[]) {
        String input = "Last word in a sentence";
        getLastWord(input);
    }
    
    public static String getLastWord(String input) {
        String lastWord;
        String wordSeparator = " ";
        boolean singleWordStr = !StringUtils.contains(input, wordSeparator);
        if (singleWordStr) {
            lastWord = input;
        }
        lastWord = StringUtils.substringAfterLast(input, wordSeparator);
        System.out.println(lastWord);
        return lastWord;
    }

3. Conclusion

To sum up, we have seen the various ways to get the last word of a Java String.

In the previous article, we have discussed Python Program to Subtract two Complex Numbers

Given a string that contains the words the task is to print the last word in the given string in Python.

Examples:

Example1:

Input:

Given string =hello this is BTechgeeks

Output:

The last word in the given string { hello this is BTechgeeks } is: BTechgeeks

Example2:

Input:

Given string =good morning this is btechgeeks

Output:

The last word in the given string { good morning this is btechgeeks } is: btechgeeks

Below are the ways to get the last word from the given string in Python.

  • Using split() Method (Static Input)
  • Using split() Method (User Input)

Method #1: Using split() Method (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Split the words of the given string to a list of words using the built-in split() function.
  • Get the last word from the above list of words using negative indexing and store it in a variable.
  • Print the last word of the given string by printing the above variable.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvnstrng = 'hello this is BTechgeeks'
# Split the words of the given string to a list of words
# using the built-in split() function.
lsttofwrds = gvnstrng.split()
# Get the last word from the above list of words using negative indexing
# and store it in a variable.
lstwrd = lsttofwrds[-1]
# Print the last word of the given string by printing the above variable.
print('The last word in the given string {', gvnstrng, '} is:', lstwrd)

Output:

The last word in the given string { hello this is BTechgeeks } is: BTechgeeks

Method #2: Using split() Method (User Input)

Approach:

  • Give the string as user input using the input() function and store it in the variable.
  • Split the words of the given string to a list of words using the built-in split() function.
  • Get the last word from the above list of words using negative indexing and store it in a variable.
  • Print the last word of the given string by printing the above variable.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in the variable.
gvnstrng = input('Enter some random string = ')
# Split the words of the given string to a list of words
# using the built-in split() function.
lsttofwrds = gvnstrng.split()
# Get the last word from the above list of words using negative indexing
# and store it in a variable.
lstwrd = lsttofwrds[-1]
# Print the last word of the given string by printing the above variable.
print('The last word in the given string {', gvnstrng, '} is:', lstwrd)

Output:

Enter some random string = good morning this is btechgeeks
The last word in the given string { good morning this is btechgeeks } is: btechgeeks

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

  • Python Program to Remove the First Occurrence of Character in a String
  • Program to Print Even Length Words in a String
  • Python Program to Print Nth word in a given String
  • Python Program to Remove all Consonants from a String

In the previous article, we have discussed Python Program to Subtract two Complex Numbers

Given a string that contains the words the task is to print the last word in the given string in Python.

Examples:

Example1:

Input:

Given string =hello this is BTechgeeks

Output:

The last word in the given string { hello this is BTechgeeks } is: BTechgeeks

Example2:

Input:

Given string =good morning this is btechgeeks

Output:

The last word in the given string { good morning this is btechgeeks } is: btechgeeks
  • Python Program to Remove the last Word from the String/Sentence
  • Python Program to Remove a String from a List of Strings
  • Python Program to Sort words in Alphabetic Order

Below are the ways to get the last word from the given string in Python.

  • Using split() Method (Static Input)
  • Using split() Method (User Input)

Method #1: Using split() Method (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Split the words of the given string to a list of words using the built-in split() function.
  • Get the last word from the above list of words using negative indexing and store it in a variable.
  • Print the last word of the given string by printing the above variable.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvnstrng = 'hello this is BTechgeeks'
# Split the words of the given string to a list of words
# using the built-in split() function.
lsttofwrds = gvnstrng.split()
# Get the last word from the above list of words using negative indexing
# and store it in a variable.
lstwrd = lsttofwrds[-1]
# Print the last word of the given string by printing the above variable.
print('The last word in the given string {', gvnstrng, '} is:', lstwrd)

Output:

The last word in the given string { hello this is BTechgeeks } is: BTechgeeks

Method #2: Using split() Method (User Input)

Approach:

  • Give the string as user input using the input() function and store it in the variable.
  • Split the words of the given string to a list of words using the built-in split() function.
  • Get the last word from the above list of words using negative indexing and store it in a variable.
  • Print the last word of the given string by printing the above variable.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in the variable.
gvnstrng = input('Enter some random string = ')
# Split the words of the given string to a list of words
# using the built-in split() function.
lsttofwrds = gvnstrng.split()
# Get the last word from the above list of words using negative indexing
# and store it in a variable.
lstwrd = lsttofwrds[-1]
# Print the last word of the given string by printing the above variable.
print('The last word in the given string {', gvnstrng, '} is:', lstwrd)

Output:

Enter some random string = good morning this is btechgeeks
The last word in the given string { good morning this is btechgeeks } is: btechgeeks

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

  • Python Program to Remove the First Occurrence of Character in a String
  • Program to Print Even Length Words in a String
  • Python Program to Print Nth word in a given String
  • Python Program to Remove all Consonants from a String

Looking at the code, it seems like you are reinventing the wheel.
See the answer of @Josiah for some alternatives to use the standard library.
Assuming this ain’t possible for some reason, lets say its implemented badly, I would improve some smaller things.

Before giving some improvements, make sure to measure!
Is this code only used once? Does it only take 1% of the time? Is the example code the only use? Than don’t spend time on this!

Add preconditions

Currently your function accepts an empty string.
When this is encountered, you always get an error message.
If you somewhere want to handle this differently, it should be checked twice.
Or in case you know it can’t be empty, it still is checked when not needed.

Instead, you could write:

assert(!str.empty() && "An empty string should not be passed");

If your specific example, you’ll have to write the check in the main function. However, in that case, you could use an alternative way of handling it. For example:

std::string str;
do
{
    std::cout << "Enter string :n";
    std::getline(std::cin, str);
} while (str.empty());

Memory allocations

std::string can have short string optimization. Although, for large strings, this might allocate memory. If you append character by character, this might reallocate.

To prevent this reallocation, you can reserve the string:

last_word.reserve(str.size() + 1 /*Null terminator*/);

The code above would be wonderful for a vector, when you have at least 1 element. However, as we have short string optimization, this might allocate, while the result won’t require it.

last_word.reserve(len — j); // To be verified with null terminator.

If really performance critical, you might want to check the implementation of the standard library as they are allowed to reserve more characters than you pass. So, they can add 1 for the null terminator. (libstdc++ and MSVC do so, I read)

Output argument

In order to not recreate a string, you can manipulate the original string.
With the erase method, you can (in bulk) remove all previous characters at once.

This will work when you don’t need that argument any more, however, this might add unwanted overhead if you do or don’t have a std::string instance.

string_view

std::string_view was added in a recent c++ version, this will behave as a string, although, doesn’t store the content in it.
Returning a string_view might prevent copying over the characters into the std::string. Same can be said for the input argument.

Warning: This is error prone in case you work with temporaries.

Понравилась статья? Поделить с друзьями:
  • Get landscape on word
  • Get images from word
  • Get html from word
  • Get him eat him one word
  • Get first word from string python