How to remove the last character from a string? - java

I want to remove the last character from a string. I've tried doing this:
public String method(String str) {
if (str.charAt(str.length()-1)=='x'){
str = str.replace(str.substring(str.length()-1), "");
return str;
} else{
return str;
}
}
Getting the length of the string - 1 and replacing the last letter with nothing (deleting it), but every time I run the program, it deletes middle letters that are the same as the last letter.
For example, the word is "admirer"; after I run the method, I get "admie." I want it to return the word admire.

replace will replace all instances of a letter. All you need to do is use substring():
public String method(String str) {
if (str != null && str.length() > 0 && str.charAt(str.length() - 1) == 'x') {
str = str.substring(0, str.length() - 1);
}
return str;
}

Why not just one liner?
public static String removeLastChar(String str) {
return removeLastChars(str, 1);
}
public static String removeLastChars(String str, int chars) {
return str.substring(0, str.length() - chars);
}
Full Code
public class Main {
public static void main (String[] args) throws java.lang.Exception {
String s1 = "Remove Last CharacterY";
String s2 = "Remove Last Character2";
System.out.println("After removing s1==" + removeLastChar(s1) + "==");
System.out.println("After removing s2==" + removeLastChar(s2) + "==");
}
public static String removeLastChar(String str) {
return removeLastChars(str, 1);
}
public static String removeLastChars(String str, int chars) {
return str.substring(0, str.length() - chars);
}
}
Demo

Since we're on a subject, one can use regular expressions too
"aaabcd".replaceFirst(".$",""); //=> aaabc

The described problem and proposed solutions sometimes relate to removing separators. If this is your case, then have a look at Apache Commons StringUtils, it has a method called removeEnd which is very elegant.
Example:
StringUtils.removeEnd("string 1|string 2|string 3|", "|");
Would result in:
"string 1|string 2|string 3"

public String removeLastChar(String s) {
if (s == null || s.length() == 0) {
return s;
}
return s.substring(0, s.length()-1);
}

Don't try to reinvent the wheel, while others have already written libraries to perform string manipulation:
org.apache.commons.lang3.StringUtils.chop()

In Kotlin you can used dropLast() method of the string class.
It will drop the given number from string, return a new string
var string1 = "Some Text"
string1 = string1.dropLast(1)

Use this:
if(string.endsWith("x")) {
string= string.substring(0, string.length() - 1);
}

if (str.endsWith("x")) {
return str.substring(0, str.length() - 1);
}
return str;
For example, the word is "admirer"; after I run the method, I get "admie." I want it to return the word admire.
In case you're trying to stem English words
Stemming is the process for reducing inflected (or sometimes derived) words to their stem, base or root form—generally a written word form.
...
A stemmer for English, for example, should identify the string "cats" (and possibly "catlike", "catty" etc.) as based on the root "cat", and "stemmer", "stemming", "stemmed" as based on "stem". A stemming algorithm reduces the words "fishing", "fished", "fish", and "fisher" to the root word, "fish".
Difference between Lucene stemmers: EnglishStemmer, PorterStemmer, LovinsStemmer outlines some Java options.

As far as the readability is concerned, I find this to be the most concise
StringUtils.substring("string", 0, -1);
The negative indexes can be used in Apache's StringUtils utility.
All negative numbers are treated from offset from the end of the string.

string = string.substring(0, (string.length() - 1));
I'm using this in my code, it's easy and simple.
it only works while the String is > 0.
I have it connected to a button and inside the following if statement
if (string.length() > 0) {
string = string.substring(0, (string.length() - 1));
}

public String removeLastChar(String s) {
if (!Util.isEmpty(s)) {
s = s.substring(0, s.length()-1);
}
return s;
}

removes last occurence of the 'xxx':
System.out.println("aaa xxx aaa xxx ".replaceAll("xxx([^xxx]*)$", "$1"));
removes last occurrence of the 'xxx' if it is last:
System.out.println("aaa xxx aaa ".replaceAll("xxx\\s*$", ""));
you can replace the 'xxx' on what you want but watch out on special chars

Look to StringBuilder Class :
StringBuilder sb=new StringBuilder("toto,");
System.out.println(sb.deleteCharAt(sb.length()-1));//display "toto"

// creating StringBuilder
StringBuilder builder = new StringBuilder(requestString);
// removing last character from String
builder.deleteCharAt(requestString.length() - 1);

How can a simple task be made complicated. My solution is:
public String removeLastChar(String s) {
return s[0..-1]
}
or
public String removeLastChar(String s) {
if (s.length() > 0) {
return s[0..-1]
}
return s
}

// Remove n last characters
// System.out.println(removeLast("Hello!!!333",3));
public String removeLast(String mes, int n) {
return mes != null && !mes.isEmpty() && mes.length()>n
? mes.substring(0, mes.length()-n): mes;
}
// Leave substring before character/string
// System.out.println(leaveBeforeChar("Hello!!!123", "1"));
public String leaveBeforeChar(String mes, String last) {
return mes != null && !mes.isEmpty() && mes.lastIndexOf(last)!=-1
? mes.substring(0, mes.lastIndexOf(last)): mes;
}

A one-liner answer (just a funny alternative - do not try this at home, and great answers already given):
public String removeLastChar(String s){return (s != null && s.length() != 0) ? s.substring(0, s.length() - 1): s;}

Most answers here forgot about surrogate pairs.
For instance, the character đť•« (codepoint U+1D56B) does not fit into a single char, so in order to be represented, it must form a surrogate pair of two chars.
If one simply applies the currently accepted answer (using str.substring(0, str.length() - 1), one splices the surrogate pair, leading to unexpected results.
One should also include a check whether the last character is a surrogate pair:
public static String removeLastChar(String str) {
Objects.requireNonNull(str, "The string should not be null");
if (str.isEmpty()) {
return str;
}
char lastChar = str.charAt(str.length() - 1);
int cut = Character.isSurrogate(lastChar) ? 2 : 1;
return str.substring(0, str.length() - cut);
}

Java 8
import java.util.Optional;
public class Test
{
public static void main(String[] args) throws InterruptedException
{
System.out.println(removeLastChar("test-abc"));
}
public static String removeLastChar(String s) {
return Optional.ofNullable(s)
.filter(str -> str.length() != 0)
.map(str -> str.substring(0, str.length() - 1))
.orElse(s);
}
}
Output : test-ab

public String removeLastCharacter(String str){
String result = null;
if ((str != null) && (str.length() > 0)) {
return str.substring(0, str.length() - 1);
}
else{
return "";
}
}

if we want to remove file extension of the given file,
** Sample code
public static String removeNCharactersFromLast(String str,int n){
if (str != null && (str.length() > 0)) {
return str.substring(0, str.length() - n);
}
return "";
}

For kotlin check out
string.dropLast(1)

if you have special character like ; in json just use String.replace(";", "") otherwise you must rewrite all character in string minus the last.

Why not use the escape sequence ... !
System.out.println(str + '\b');
Life is much easier now . XD ! ~ A readable one-liner

How to make the char in the recursion at the end:
public static String removeChar(String word, char charToRemove)
{
String char_toremove=Character.toString(charToRemove);
for(int i = 0; i < word.length(); i++)
{
if(word.charAt(i) == charToRemove)
{
String newWord = word.substring(0, i) + word.substring(i + 1);
return removeChar(newWord,charToRemove);
}
}
System.out.println(word);
return word;
}
for exemple:
removeChar ("hello world, let's go!",'l') → "heo word, et's go!llll"
removeChar("you should not go",'o') → "yu shuld nt goooo"

Here's an answer that works with codepoints outside of the Basic Multilingual Plane (Java 8+).
Using streams:
public String method(String str) {
return str.codePoints()
.limit(str.codePoints().count() - 1)
.mapToObj(i->new String(Character.toChars(i)))
.collect(Collectors.joining());
}
More efficient maybe:
public String method(String str) {
return str.isEmpty()? "": str.substring(0, str.length() - Character.charCount(str.codePointBefore(str.length())));
}

just replace the condition of "if" like this:
if(a.substring(a.length()-1).equals("x"))'
this will do the trick for you.

Suppose total length of my string=24
I want to cut last character after position 14 to end, mean I want starting 14 to be there.
So I apply following solution.
String date = "2019-07-31T22:00:00.000Z";
String result = date.substring(0, date.length() - 14);

I had to write code for a similar problem. One way that I was able to solve it used a recursive method of coding.
static String removeChar(String word, char charToRemove)
{
for(int i = 0; i < word.lenght(); i++)
{
if(word.charAt(i) == charToRemove)
{
String newWord = word.substring(0, i) + word.substring(i + 1);
return removeChar(newWord, charToRemove);
}
}
return word;
}
Most of the code I've seen on this topic doesn't use recursion so hopefully I can help you or someone who has the same problem.

Related

How to use recursion to create a searies of substrings in java

So, the task is to create a string that makes a progression throughout the letters of a string, returning a substring progressively longer.
For example if the input is Book, the answer would be: BBoBooBook . For the input Soup the method would return SSoSouSoup. I want to write it recursively. In my current method I receive no error but at the same time no anwer from the compiler.
public static String stringProgression(String str) {
int index = 1;
String result = "";
if (str.length() == 0) {
return "" ;
} else while (index <= str.length()); {
result = result + stringExplosion(str.substring(0, index));
index++;
}
return result;
}
In your code, you are using two different method names, stringProgression and stringExplosion.
Further, you have a while loop with a semicolon, while (index <= str.length()); which forms an empty loop. Since index doesn’t change in this empty loop, it will be an infinite loop when the condition is fulfilled.
Generally, a while loop contradicts the intent to have a recursive solution.
To find a recursive solution to a problem, you have to find the self-similarity in it. I.e. when you look at the intended result for Book, BBoBooBook, you can recognize that the beginning, BBoBoo is the right result for the string Boo, and BBo is the right result for Bo. So, the original string has to be appended to the result of a recursive evaluation of the substring:
public static String stringProgression(String str) {
if(str.isEmpty()) {
return str;
}
return stringProgression(str.substring(0, str.length() - 1)) + str;
}
An alternative, shorter syntax for the same is:
public static String stringProgression(String str) {
return str.isEmpty()? str: stringProgression(str.substring(0, str.length() - 1)) + str;
}
Check this one:
private static String doStringProgression(String str, String res, int length) {
if(length > str.length()) {
return res;
}
return doStringProgression(str, res + str.substring(0, length), length + 1);
}
And you can call the method with input like in the following example:
public static String stringProgression(String str) {
return doStringProgression(str, "", 1);
}

replacing pi with 3.14 in a String recursively (no loops)

Given a string, compute recursively (no loops) a new string where all appearances of "pi" have been replaced by "3.14".
changePi("xpix") → "x3.14x"
changePi("pipi") → "3.143.14"
changePi("pip") → "3.14p"
My code worked perfectly but is there any other way (only recursively no loops) to do this problem without having to create a new string str2 ?
Thank you in advance
here is my code :
public String changePi(String str) {
String str2 = "";
return changePi(str, str2);
}
public String changePi(String str, String str2) {
if (str.length() == 0)
return str2;
else {
if (str.endsWith("pi")) {
str2 = 3.14 + str2;
return changePi(str.substring(0, str.length() - 2), str2);
} else
str2 = str.charAt(str.length() - 1) + str2;
}
return changePi(str.substring(0, str.length() - 1), str2);
}
Using the same mechanism you can use a StringBuilder and modify it in-situ. This should be much more memory efficient.
private static final String PI = "pi";
private static final String THREE_POINT_ONE_FOUR = "3.14";
public String changePi(String s) {
// Work with a StringBuilder for efficiency.
StringBuilder sb = new StringBuilder(s);
// Start replacement at 0.
return changePi(sb, 0).toString();
}
private StringBuilder changePi(StringBuilder sb, int i) {
// Long enough?
if (i + PI.length() <= sb.length()) {
// Is it there?
if (sb.subSequence(i, i + PI.length()).equals(PI)) {
// Yes! - Replace it and recurse.
sb.replace(i, i + PI.length(), THREE_POINT_ONE_FOUR);
return changePi(sb, i + THREE_POINT_ONE_FOUR.length());
} else {
// Not there - step to next.
return changePi(sb, i + 1);
}
}
return sb;
}
private void test(String s) {
System.out.println(s + " -> " + changePi(s));
}
private void test() {
test("pipi");
test("xpix");
test("pip");
}
You are doing the same mistake as you did in your previous question. Also I would prefer to check if a string starts with, and not ends with a string...I am assuming that you would like something that you can understand and it's easy to explain.
Can you match "pi" or the string is already less than length("pi") symbols -> cant do nothing much so return it.
Does it starts with "pi"? If so return the replacement concatenated with the rest of the string (just the rest starts length("pi") characters away from the 0th index...
If it isn't starting with "pi" than concatenate the first character with what's the output of changePi and the rest of the string as its input.
public static String changePi(String str) {
if (str.length() < "pi".length()) {
return str;
}
if (str.startsWith("pi")) {
return "3.14" + changePi(str.substring("pi".length(), str.length()));
}
return str.charAt(0) + changePi(str.substring(1, str.length()));
}
And still if you like to use the "endsWith" logic then here is the same algorythm applied.
public static String changePi(String str) {
if (str.length() < "pi".length()) {
return str;
}
if (str.endsWith("pi")) {
return changePi(str.substring(0, str.length() - "pi".length())) + "3.14";
}
return changePi(str.substring(0, str.length() - 1)) + str.charAt(str.length() - 1);
}
public static String changePi(String str) {
int num = str.indexOf("pi");
if (num==-1) return str;
return str.substring(0,num)+"3.14"+changePi(str.substring(num+2));
}
does it, though I guess it depends what you mean by create a new string. In a sense this does, but without naming it.
Your solution is a nice approach (it's a little confusing as you replace twice, I believe) and I would make sth like:
If str <= than 2, check str if equals pi, return 3,14 or str
Else, if ends with pi return Change(str-2)+Change(last2), else return Change(str-1)+Change(lastChar)
Edited: now changes pi for 3,14
Voila! simple and clean:
String fun(int i) {
if(i == s.length()) return "";
if(i+1 < s.length() && s.charAt(i) == 'p' && s.charAt(i+1) == 'i') {
return "3.14" + fun(i+2);
} else {
return s.charAt(i) + fun(i+1);
}
}
Any reason why you have not considered using regular expressions?
The following seems to work fine for all the test cases you mentioned:
public String changePi(String str) {
return str.replaceAll("pi", "3.14");
}
Note that in Java a String is immutable. You cannot modify a String once you initialise it. Each time you are doing str2 = ... you are really creating a completely new String object.
If you need to do it recursively (i.e. it is some coursework), then what you did is perfectly fine (although I would have used indexOf("pi") rather than endsWith("pi") and removing the trailing characters, but anyway.
It is the standard way to perform recursion, with str2 being the accumulator (maybe you want to rename it so that it is clear what it is doing). You might want to consider using StringBuilder instead of a String for the second parameter, and in your base case you call toString() to get the final string... although honestly the difference in computation cost between creating a new String and using a StringBuilder has become very low.
I've never written Java before, but this seems to work:
public class HelloWorld {
public static void main(String[] args) {
System.out.println(changePi("xpix"));
System.out.println(changePi("pipi"));
System.out.println(changePi("pip"));
}
public static String changePi(String str) {
int len = str.length();
if (len < 2)
return str;
if (str.endsWith("pi"))
return changePi(str.substring(0, len - 2)) + "3.14";
else
return changePi(str.substring(0, len - 1)) + str.substring(len - 1, len);
}
}
Explaination:
This is closer to a true recursive solution, since the function doesn't know about the right portion of the string (no str2), it's the calling function's responsibility to keep track of it.
The terminal case is running on a string shorter than "pi", in which case we return the remainder (0 or 1 chars).
If the string ends in "pi", we take the rest of the string before that and pass that to the new iteration, but keep in mind to append "3.14" when that returns.
If the string doesn't end in that, we just break off a single character and keep it to reattach.
Criticism:
This is horribly inefficient, though, as every .substr call is creating a whole new string object, and we do a lot of these calls.
You would have better luck using something like a linked list of characters.
public String changePi(String str) {
if(str.length() == 0){
return str;
}
if(str.startsWith("pi")){
return "3.14" + changePi(str.substring(2));
}
return str.substring(0,1) + changePi(str.substring(1));
}
public class ChangePi {
public static String changePi(String str) {
String pi = "3.14";
if (str.length() < 2) {
return str;
}
return (str.substring(0, 2).equals("pi")) ? pi + changePi(str.substring(2)) :
str.substring(0, 1) + changePi(str.substring(1));
}
}
Hope my answer explains everything :)
public String changePi(String str) {
if (str.length() < 1) return ""; // return if string length is zero
String count = str.substring(0,1); // get the string
int increment = 1; // increment variable to iterate the string
if (str.length() > 1 && str.substring(0, 2).equals("pi")){
//string length > 1 and it pi if found
count = "3.14";
increment = 2;//increment by 2 characters
}
//attach the 3.14 part or substring(0,1) and move forward in the string
return count + changePi(str.substring(increment));
}
Here is the answer:
public String changePi(String str) {
if(str.equals("")){
return str;
}
else if(str.length()>=2 && str.charAt(0)=='p' && str.charAt(1)=='i') {
return "3.14" + changePi(str.substring(2));
}
else{
return str.charAt(0) + changePi(str.substring(1));
}
}
public String changePi(String str) {
if(str.length() == 0) return str;
if(str.charAt(0) == 'p' && str.length() >= 2){
if(str.charAt(1) == 'i'){
return "3.14" + changePi(str.substring(2));
}
}
return str.charAt(0) + changePi(str.substring(1));
}

Trim leading or trailing characters from a string?

How can I trim the leading or trailing characters from a string in java?
For example, the slash character "/" - I'm not interested in spaces, and am looking to trim either leading or trailing characters at different times.
You could use
Leading:
System.out.println("//test/me".replaceAll("^/+", ""));
Trailing:
System.out.println("//test/me//".replaceAll("/+$", ""));
You can use Apache StringUtils.stripStart to trim leading characters, or StringUtils.stripEnd to trim trailing characters.
For example:
System.out.println(StringUtils.stripStart("//test/me", "/"));
will output:
test/me
Note that if for some reason you can't use the whole StringUtils library, you could just rip out the relevant parts, as detailed here:
Trim with Character, String, or Regex
If run-time is not a big issue for you, then this code will prove really helpful.
public class StringTrimmer {
public static String trim(String string, char ch){
return trim(string, ch, ch);
}
public static String trim(String string, char leadingChar, char trailingChar){
return string.replaceAll("^["+leadingChar+"]+|["+trailingChar+"]+$", "");
}
public static String trim(String string, String regex){
return trim(string, regex, regex);
}
public static String trim(String string, String leadingRegex, String trailingRegex){
return string.replaceAll("^("+leadingRegex+")+|("+trailingRegex+")+$", "");
}
// test
public static void main(String[] args) {
System.out.println(trim("110100", '1', '0')); // outputs: 01
System.out.println(trim("**Aa0*#**", '*')); // outputs: Aa0*#
System.out.println(trim("123##22222", "12", "22")); // outputs: 3##2
System.out.println(trim("101101##10101", "101")); // outputs: ##10
System.out.println(trim("123##abcde", "\\d", "[c-e]")); // outputs: ##ab
}
}
You could use a simple iteration if you want to remove the leading characters from a string :
String removeLeadingChar(String s, char c) {
int i;
for(i = 0; i < s.length() && s.charAt(i) == c; ++i);
return s.substring(i);
}
same logic applies if you want to remove any trailing char.
For those using Spring:
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/StringUtils.html#trimTrailingCharacter-java.lang.String-char-
import org.springframework.util.StringUtils;
public void setFileName(String fileName) {
// If the extension does not exist trim the trailing period
this.fileName = StringUtils.trimTrailingCharacter(fileName,'.');
}
My version of trimming leading and/or trailing String s from String str. Both arguments may be null. When str does not has leading and/or trailing s, it is not changed.
String trim(String str, String s) {
String res = s == null ? str : str == null ? null : s.length() >= str.length() ? str : str.replaceFirst(s, "");
if ((res != null) && (s != null) && (res.length() >= s.length())) {
return res.substring(res.length() - s.length(), res.length()).equals(s) ? res.substring(0, res.length() - s.length()) : res;
}
return res;
}

How to remove only trailing spaces of a string in Java and keep leading spaces?

The trim() function removes both the trailing and leading space, however, if I only want to remove the trailing space of a string, how can I do it?
Since JDK 11
If you are on JDK 11 or higher you should probably be using stripTrailing().
Earlier JDK versions
Using the regular expression \s++$, you can replace all trailing space characters (includes space and tab characters) with the empty string ("").
final String text = " foo ";
System.out.println(text.replaceFirst("\\s++$", ""));
Output
foo
Online demo.
Here's a breakdown of the regex:
\s – any whitespace character,
++ – match one or more of the previous token (possessively); i.e., match one or more whitespace character. The + pattern is used in its possessive form ++, which takes less time to detect the case when the pattern does not match.
$ – the end of the string.
Thus, the regular expression will match as much whitespace as it can that is followed directly by the end of the string: in other words, the trailing whitespace.
The investment into learning regular expressions will become more valuable, if you need to extend your requirements later on.
References
Java regular expression syntax
Another option is to use Apache Commons StringUtils, specifically StringUtils.stripEnd
String stripped = StringUtils.stripEnd(" my lousy string "," ");
I modified the original java.lang.String.trim() method a bit and it should work:
public String trim(String str) {
int len = str.length();
int st = 0;
char[] val = str.toCharArray();
while ((st < len) && (val[len - 1] <= ' ')) {
len--;
}
return str.substring(st, len);
}
Test:
Test test = new Test();
String sample = " Hello World "; // A String with trailing and leading spaces
System.out.println(test.trim(sample) + " // No trailing spaces left");
Output:
Hello World // No trailing spaces left
As of JDK11 you can use stripTrailing:
String result = str.stripTrailing();
The most practical answer is #Micha's, Ahmad's is reverse of what you wanted so but here's what I came up with in case you'd prefer not to use unfamiliar tools or to see a concrete approach.
public String trimEnd( String myString ) {
for ( int i = myString.length() - 1; i >= 0; --i ) {
if ( myString.charAt(i) == ' ' ) {
continue;
} else {
myString = myString.substring( 0, ( i + 1 ) );
break;
}
}
return myString;
}
Used like:
public static void main( String[] args ) {
String s = " Some text here ";
System.out.println( s + "|" );
s = trimEnd( s );
System.out.println( s + "|" );
}
Output:
Some text here |
Some text here|
The best way in my opinion:
public static String trimEnd(String source) {
int pos = source.length() - 1;
while ((pos >= 0) && Character.isWhitespace(source.charAt(pos))) {
pos--;
}
pos++;
return (pos < source.length()) ? source.substring(0, pos) : source;
}
This does not allocate any temporary object to do the job and is faster than using a regular expression. Also it removes all whitespaces, not just ' '.
Here's a very short, efficient and easy-to-read version:
public static String trimTrailing(String str) {
if (str != null) {
for (int i = str.length() - 1; i >= 0; --i) {
if (str.charAt(i) != ' ') {
return str.substring(0, i + 1);
}
}
}
return str;
}
As an alternative to str.charAt(i) != ' ' you can also use !Character.isWhitespace(str.charAt(i) if you want to use a broader definition of whitespace.
Spring framework gives a useful org.springframework.util.StringUtils.
trimTrailingWhitespace
This code is intended to be read a easily as possible by using descriptive names (and avoiding regular expressions).
It does use Java 8's Optional so is not appropriate for everyone.
public static String removeTrailingWhitspace(String string) {
while (hasWhitespaceLastCharacter(string)) {
string = removeLastCharacter(string);
}
return string;
}
private static boolean hasWhitespaceLastCharacter(String string) {
return getLastCharacter(string)
.map(Character::isWhitespace)
.orElse(false);
}
private static Optional<Character> getLastCharacter(String string) {
if (string.isEmpty()) {
return Optional.empty();
}
return Optional.of(string.charAt(string.length() - 1));
}
private static String removeLastCharacter(String string) {
if (string.isEmpty()) {
throw new IllegalArgumentException("String must not be empty");
}
return string.substring(0, string.length() - 1);
}
String value= "Welcome to java ";
So we can use
value = value.trim();

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?
Why not just String substr = word.substring(word.length() - 3)?
Update
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!");
}
I would consider right method from StringUtils class from Apache Commons Lang:
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#right(java.lang.String,%20int)
It is safe. You will not get NullPointerException or StringIndexOutOfBoundsException.
Example usage:
StringUtils.right("abcdef", 3)
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 {
last3 = str.substring(str.length() - 3);
}
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.
Here is a method I use to get the last xx of a string:
public static String takeLast(String value, int count) {
if (value == null || value.trim().length() == 0 || count < 1) {
return "";
}
if (value.length() > count) {
return value.substring(value.length() - count);
} else {
return value;
}
}
Then use it like so:
String testStr = "this is a test string";
String last1 = takeLast(testStr, 1); //Output: g
String last4 = takeLast(testStr, 4); //Output: ring
This method would be helpful :
String rightPart(String text,int length)
{
if (text.length()<length) return text;
String raw = "";
for (int i = 1; i <= length; i++) {
raw += text.toCharArray()[text.length()-i];
}
return new StringBuilder(raw).reverse().toString();
}
The getChars string method does not return a value, instead it dumps its result into your buffer (or destination) array. The index parameter describes the start offset in your destination array.
Try this link for a more verbose description of the getChars method.
I agree with the others on this, I think substring would be a better way to handle what you're trying to accomplish.
You can use a substring
String word = "onetwotwoone"
int lenght = word.length(); //Note this should be function.
String numbers = word.substring(word.length() - 3);
Alternative way for "insufficient string length or null" save:
String numbers = defaultValue();
try{
numbers = word.substring(word.length() - 3);
} catch(Exception e) {
System.out.println("Insufficient String length");
}
This method will return the x amount of characters from the end.
public static String lastXChars(String v, int x) {
return v.length() <= x ? v : v.substring(v.length() - x);
}
//usage
System.out.println(lastXChars("stackoverflow", 4)); // flow

Categories

Resources