×

How to remove last character from String in Java

In java, there are predominantly three classes connected with the string. The classes are String, StringBuilder, and StringBuffer class that gives techniques connected with string control. Eliminating the first and last character from the string is likewise an activity that we can perform on the string.

There are four methods for eliminating the last character from a string:

  1. StringBuffer.deleteCahrAt() Class
  2. String.substring() Method
  3. StringUtils.chop() Method
  4. Regular Expression

StringBuffer class

StringBuffer is a companion class of strings that gives a large part of the usefulness of strings. The string addresses fixed-length, unchanging person groupings while StringBuffer addresses growable and writable person successions. StringBuffer might have characters and substrings embedded in the centre or affixed as far as possible. It will naturally develop to account for such increases and frequently has a larger number of characters preallocated than are really required to permit space for development.

Constructors of StringBuffer class

1. StringBuffer(): It holds space for 16 characters without redistribution

     StringBuffer s1 = new StringBuffer();

2. StringBuffer( int size): It acknowledges a whole number contention that expressly sets the size of the cradle.

     StringBuffer s2 = new StringBuffer(20);

3. StringBuffer(String str): It acknowledges a string contention that sets the underlying items in the StringBuffer object and stores space for 16 additional characters without redistribution.          

     StringBuffer s3 = new StringBuffer("Hello !!! World");

Methods of StringBuffer class

append(): Used to add text toward the finish of the current text.

Length (): The length of a StringBuffer can be tracked down by the length( ) strategy

capacity(): All-out distributed limit can be tracked down by the limit( ) strategy

delete(): Erases a grouping of characters from the summoning object delete.

CharAt(): Erases the person at the file determined by loc

ensureCapacity(): Guarantees limit is essentially equivalent to the given least.

Insert (): Guarantee limit is essentially equivalent to the given least.

length():  Returns the length of the string

reverse(): Invert the characters inside a StringBuffer object

replace(): Supplant one bunch of characters with one more set inside a StringBuffer          object

The StringBuffer class gives a technique deleteCharAt(). The technique erases a person from the predetermined position. We utilize the technique to eliminate a character from a string in java. It acknowledges a boundary list of type int. The list is the place of a person we need to erase. It returns this object.

Syntax: 

public StringBuffer deleteCharAt(int index)  

Example

public class RemoveLastCharcterEx  
{ 
public static void main(String args[])  
{  
String str = "Hello !!! World";  
//constructor of StringBuffer class  
StringBuffer sb= new StringBuffer(str);  
sb.deleteCharAt(sb.length()-1);  
//prints the string after deleting the character   
System.out.println(sb);  
}  
}  

Output

How to Remove Last Character from String in Java

String.substring() Method

The Java String class substring() technique returns a piece of the string. We pass the beginIndex and endIndex number situation in the Java substring strategy where beginIndex is comprehensive, and endIndex is restrictive. All in all, the beginIndex begins from 0, while the endIndex begins from 1.

There are two sorts of substring techniques in Java string.

  1. public String substring(int startIndex) 
  2. public String substring(int startIndex, int endIndex) 

Accepting that the beginIndex is negative or beginIndex > endIndex or the endIndex > length of the string it throws IndexOutOfBoundsException.

The substring() is the technique for the String class. It parses two boundaries, beginIndex and endIndex of type int. It returns another string (sub-string). It isn't strung safely because it doesn't toss a special case assuming the string is invalid or void.

Example

public class RemoveLastCharacterEx 
{  
public static void main(String[] args)   
{  
//object of the class  
RemoveLastCharacterEx R1 = new RemoveLastCharacterEx();  
String str="Hello !!! World";  
//method calling  
str=R1.removeLastChar(str);        
System.out.println(string);  
}  
private String removeLastChar(String s)   
{  
// returns the string in the wake of eliminating the last person
return s.substring(0, s.length() - 1);  
}   
}

Output

How to Remove Last Character from String in Java

StringUtils.chop() Method

The StringUtils class gives a chop() technique to eliminate the last person from a string. The technique parses a boundary of type String. It likewise acknowledges invalid as a parameter. It returns the string subsequent to eliminating the last person. It likewise returns an invalid string when we input an invalid string.

Syntax:

public static String chop(String str) 

For utilizing the chop() technique for the StringUtils class, we want to add the accompanying reliance in the pom.xml document. At the point when we add the Apache lodge lang3 container in the pom document, it downloads the container record and adds the container record to the way. We should import the bundle org.apache.commons.lang3.StringUtils.

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

Example

import org.apache.commons.lang3.StringUtils;  
public class RemoveLastCharacter3
{  
public static void main(String[] args)   
{  
String string=" Google";  
//invoking method  
s=StringUtils.chop(string);  
System.out.println(s);  
}  
}  

Output

How to Remove Last Character from String in Java

Regular Expression

A regular expression is a succession of characters that frames a hunting design. At the point when you look for information in a text, you can utilize this search example to portray what you are looking for. A regular expression can be a solitary person or a more convoluted design. a Regular expression can be utilized to play out a wide range of text search and text supplant tasks. Java doesn't have an underlying Regular Expression class, yet we can import the java.util.regex bundle to work with standard articulations. The bundle incorporates the accompanying classes:

  • Pattern Class - Defines an example (to be utilized in a hunt)
  • Matcher Class - Used to look for the example
  • PatternSyntaxException Class - Indicates syntax error in a standard articulation design.

We can likewise utilize the regular expression to eliminate or erase the last person from the string. The String class gives the replaceAll() technique that parses two boundaries regex and substitution of type String. The strategy replaces the string with the predefined match.

  • Regex: It is the verbalization with which the string is arranged.
  • Replacement: It is the exchange string or substitute string for each match.

It returns the subsequent substring.

Syntax:  

public String replaceAll(String regex, String replacement) 

Example

public class RemoveLastCharEx
{  
public static void main(String[] args)   
{  
//creating an object of the class  
RemoveLastCharEx R1=new RemoveLastCharEx ();  
String str="Honesty is the best policy";  
//method calling  
str=R1.removeLastCharacter(string);  
//prints the string  
System.out.println(str);  
}  
public String removeLastChar(String str)   
{  
// the replaceAll() strategy eliminates the string and returns the string return (str == null) ? null : str.replaceAll(".!$", "");  
}  
}  

Output:

How to Remove Last Character from String in Java

Related Topics

Deque in Java

Deque in java collections with Example Deque is short for “double-ended queue.” It is a linear collection that extends the Queue interface and supports insertion and deletion of the element at both the...

3 minutes read.

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.

Ordinal Number in Java

What is the Ordinal Number in Java? An object's or person's position or rank can be expressed mathematically using an ordinal number. Depending on the criteria used to establish the positions,...

3 minutes read.

Java Integer toHexString() method

The toHexString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 16. Syntax public static String toHexString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

Java Code Coverage Tools

Code coverage testing is a crucial metric that gauges how thoroughly the program's source code has been tested. The market is flooded with Code Coverage Tools, making it difficult to...

7 minutes read.

How to reverse a linked list in java

The process of reversing a linked list in Java will be covered in this section. One of the most common questions in interviews is about reversing a linked list. If...

11 minutes read.

Java Full Stack

A person who can create both the front end and back end of an application is a full-stack developer. In essence, the term "Java full-stack" refers to a web developer...

9 minutes read.

Awesome explanation of Strings in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

How to Convert String to Date in Java

How to Convert String to Date in java You can convert String to Date in Java by using the parse() method. There are two classes which have parse() method namely, DateFormat and SimpleDateFormat classes....

2 minutes read.

Java Characters

Normally, when we work with characters, we use primitive data types char. When we have to work with the objects of char, we use Character class. Character class has many important...

2 minutes read.

How to Convert Hexadecimal to Decimal in Java

How to Convert Hexadecimal to Decimal in Java There are two methods to convert Hexadecimal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method It is a static method of...

2 minutes read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Access specifiers in Java

What are access specifiers in Java? Access specifiers in Java are used to determine whether other classes can use a particular field or invoke a particular method. Access specifiers mainly specify...

7 minutes read.

What are Array strings in Java?

In normal programming, An array is a group and a collection of identical forms of data that are stored in a sequential memory region and may be accessed using their...

4 minutes read.

Sorting Algorithms in Java

Sorting Algorithms in Java Sorting is the technique that puts the elements of an array or list either in descending or ascending order. For example, take an array A, whose elements...

3 minutes read.

ConcurrentSkipListSet in Java

ConcurrentSkipListSet is a class that is a part of collection framework in Java.It has been available since Java version 1.6. ConcurrentSkipListSet  is a scalable concurrent NavigableSet implementation based on a ConcurrentSkipListMap.The...

16 minutes read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular...

6 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.