Java string get last symbol

Last substring of string

In Java we have indexOf and lastIndexOf . Is there anything like lastSubstring ? It should work like :

indexOf and lastIndexOf both take a string and find it without the main string, returning the location. You seem to be describing the opposite; you want a version of substring() that counts from the end instead of the beginning

7 Answers 7

Not in the standard Java API, but .

Apache Commons has a lot of handy String helper methods in StringUtils

just grab a copy of commons-lang.jar from commons.apache.org

Generalizing the other responses, you can implement lastSubstring as follows:

s.substring(s.length()-endIndex,s.length()-beginIndex); 
String string = "aaple"; string.subString(string.length() - 1, string.length()); 

You can use String.length() and String.length() — 1

For those looking to get a substring after some ending delimiter, e.g. parsing file.txt out of /some/directory/structure/file.txt

public static String substringAfterLast(String str, String separator) Gets the substring after the last occurrence of a separator. The separator is not returned. A null string input will return null. An empty ("") string input will return the empty string. An empty or null separator will return the empty string if the input string is not null. If nothing is found, the empty string is returned. StringUtils.substringAfterLast(null, *) = null StringUtils.substringAfterLast("", *) = "" StringUtils.substringAfterLast(*, "") = "" StringUtils.substringAfterLast(*, null) = "" StringUtils.substringAfterLast("abc", "a") = "bc" StringUtils.substringAfterLast("abcba", "b") = "a" StringUtils.substringAfterLast("abc", "c") = "" StringUtils.substringAfterLast("a", "a") = "" StringUtils.substringAfterLast("a", "z") = "" 

Источник

Java: Simplest way to get last word in a string

What is the simplest way to get the last word of a string in Java? You can assume no punctuation (just alphabetic characters and whitespace).

Fastest and simplest for coding and reading. Execution time is irrelevant. As an aside, having different wording is better for search purposes although the discrepancy was unintentional.

7 Answers 7

String test = "This is a sentence"; String lastWord = test.substring(test.lastIndexOf(" ")+1); 

One line is nice since I will be using it in Velocity template code. Could be combined with a regular expession to account for other characters like JST’s solution.

Actually this is better, it already accounts for a single word: String lastWord = test.substring(test.lastIndexOf(» «)+1);

String testString = "This is a sentence"; String[] parts = testString.split(" "); String lastWord = parts[parts.length - 1]; System.out.println(lastWord); // "sentence" 

This is the solution I probably would have come up with on my own, not bad, but a one-liner would be better.

When you say «fastest,» do you mean shortest in code or fastest to execute? This could be made into a one liner, but it wouldn’t execute any faster and would be much harder to read.

I did not say «fastest», I said «simplest», by which I meant a combination of brevity and ease of understanding.

@Muhd If it were me, I would think the above is easiest to read. Then again, this is also the solution I immediately came up with. @OscarRyz’s solution is also simple to read, so it comes down to personal preference.

@Dave Probably mine, is not easier to read anymore for I have added a check in case the string it self is the last word.

Here is a way to do it using String ‘s built-in regex capabilities:

String lastWord = sentence.replaceAll("^.*?(\\w+)\\W*$", "$1"); 

The idea is to match the whole string from ^ to $ , capture the last sequence of \w+ in a capturing group 1, and replace the whole sentence with it using $1 .

Edge case: This fails in right-to-left languages (ex. Hebrew). @OscarRyz substring method still works. ideone.com/MacH0s

If other whitespace characters are possible, then you’d want:

You can do that with StringUtils (from Apache Commons Lang). It avoids index-magic, so it’s easier to understand. Unfortunately substringAfterLast returns empty string when there is no separator in the input string so we need the if statement for that case.

public static String getLastWord(String input) < String wordSeparator = " "; boolean inputIsOnlyOneWord = !StringUtils.contains(input, wordSeparator); if (inputIsOnlyOneWord) < return input; >return StringUtils.substringAfterLast(input, wordSeparator); > 

Get the last word in Kotlin:

Источник

Get the last three chars from any string — Java

I’m trying to take the last three chracters of any string and save it as another String variable. I’m having some tough time with my thought process.

String word = "onetwotwoone" int length = word.length(); String new_word = id.getChars(length-3, length, buffer, index); 

I don’t know how to use the getChars method when it comes to buffer or index. Eclipse is making me have those in there. Any suggestions?

The buffer is a char[] where the characters will go, and index is the start of that array where you want to start the copy. Just create a char[] of size 3 and set index to 0. Although substring would probably be better

12 Answers 12

Why not just String substr = word.substring(word.length() — 3) ?

Please make sure you check that the String is at least 3 characters long before calling substring() :

if (word.length() == 3) < return word; >else if (word.length() > 3) < return word.substring(word.length() - 3); >else < // whatever is appropriate in this case throw new IllegalArgumentException("word has fewer than 3 characters!"); >

Might have to be careful with strings with less than three characters, I think negative inputs will return the original string (could be wrong about that), which may or may not be acceptable for what they’re trying to accomplish.

@celestialorb, Thanks for the mention, anyway the initial code from the question also has to handle exceptions, so I wasn’t thinking about this issue.

Negative index is easily avoided using Math.max() like this String substr = word.substring(Math.max(0, word.length() — 3));

why answering questions with questions? you don’t expect that he has a reason for not using the substring. probably he doesn’t know that yet.

It is safe. You will not get NullPointerException or StringIndexOutOfBoundsException .

You can find more examples under the above link.

Here’s some terse code that does the job using regex:

String last3 = str.replaceAll(".*?(. )?$", "$1"); 

This code returns up to 3; if there are less than 3 it just returns the string.

This is how to do it safely without regex in one line:

String last3 = str == null || str.length() < 3 ? str : str.substring(str.length() - 3); 

By "safely", I mean without throwing an exception if the string is nulls or shorter than 3 characters (all the other answers are not "safe").

The above code is identical in effect to this code, if you prefer a more verbose, but potentially easier-to-read form:

String last3; if (str == null || str.length() < 3) < last3 = str; >else

Possible, but quite difficult to understand with its ternary operator and lack of parentheses. So I'd advise against that here. -1.

@MvG so this answer is "not helpful"? (That's what a -1 vote means). Why is the use of ternary syntax not helpful? And where would you put brackets? On the contrary, I think this answer is helpful, especially considering all the others would explode if handed a null or a short input.

Not helpful because I believe (sorry if I'm wrong there) that most users who struggle with how to extract a substring from a given string, will be in way over their head trying to read your code. Checking length is all very fine, but at this level I'd consider more verbose solutions helpful, and cryptic solutions only confusing. As to parentheses: I'd write this … = ((… || …) ? … : …) . The line wrap you added makes things a lot better, too.

After looong time, but still would like to comment. @Bohemian's is perfect and should accepted answer.

String newString = originalString.substring(originalString.length()-3);

public String getLastThree(String myString) < if(myString.length() >3) return myString.substring(myString.length()-3); else return myString; > 

If you want the String composed of the last three characters, you can use substring(int) :

String new_word = word.substring(word.length() - 3); 

If you actually want them as a character array, you should write

char[] buffer = new char[3]; int length = word.length(); word.getChars(length - 3, length, buffer, 0); 

The first two arguments to getChars denote the portion of the string you want to extract. The third argument is the array into which that portion will be put. And the last argument gives the position in the buffer where the operation starts.

If the string has less than three characters, you'll get an exception in either of the above cases, so you might want to check for that.

Источник

How do I get the last character of a string?

You've got several questions mixed up together. Broadly, yes, str.charAt(str.length() - 1) is usually the last character in the string; but consider what happens if str is empty, or null.

Its working fine. But logic of palidrome check is doesn't sound correct, please also mention what is the error you are getting.

12 Answers 12

The output of java Test abcdef :

returns it as a string, not a character, but you already know how to do the latter, and I'm not clear on what you're after.

Question asks for a character - this returns a one character long string. Should use charAt() not substring()

Andrew, if you look back at the original question before it was edited, you'll see that the OP already tried charAt() and it wasn't what she wanted. That's one of the problems with a wiki-like medium such as SO, the questions are a moving target and sometimes the answers can look silly as a result.

Here is a method using String.charAt() :

String str = "India"; System.out.println("last char mt24">
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)">edited Mar 6, 2018 at 11:43
Callum Luke Vernon
2752 gold badges3 silver badges16 bronze badges
answered Oct 23, 2012 at 7:20
1
    1
    be really careful if you are wanting to do a calculation on a number within a string as char values are quite different than a literal number and your math results will not work.
    – JesseBoyd
    Apr 9, 2018 at 14:42
Add a comment|
72

The other answers are very complete, and you should definitely use them if you're trying to find the last character of a string. But if you're just trying to use a conditional (e.g. is the last character 'g'), you could also do the following:

if (str.endsWith("g")) 

Note that the result will be true if the argument is the empty string or is equal to this String object as determined by the equals(Object) method.

Источник

Читайте также:  Javascript and redirect to url
Оцените статью