0

I need to eliminate the last character of the string of 's'

I have tried to use a variable to have it set to the last character and used that variable to put it in the parameters of the subscript but I get an error when doing so.

public static void noLast(String s){
char last = s.charAt(s.length() - 1);
System.out.println(s.substring(0,last));

java.lang.StringIndexOutOfBoundsException: begin 0, end 108, length 5

This is the error I get when I put the string variable as 'hello' and try to eliminate the 'o'

Anoop R Desai
  • 712
  • 5
  • 18
Ben Greer
  • 11
  • 1
  • 2
  • 1
    Check the javadoc of the method [`String.substring(int, int)`](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)). You need to pass the indexes not characters – AxelH Aug 30 '19 at 05:14
  • Try if(s.length()> 0)System.out.println(s.substring(0, s.length()-1) – Srikanth Aug 30 '19 at 05:16

5 Answers5

5

All you need is

System.out.println(s.substring(0,s.length()-1));

There is no need to actually fetch the last character.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
1

Signature of String.substring

substring(beginIndex,lastIndex)

Javadoc

So, if you put character in parameter, it converted 'l' into ASCII code 108 automatically that's why you got StringIndexOutOfBoundsException at end 108.

So, just use like that -

System.out.println(s.substring(0,s.length()-1));
AxelH
  • 14,325
  • 2
  • 25
  • 55
Krishna Vyas
  • 1,009
  • 8
  • 25
0

I can offer a regex approach:

String input = "The quick brown fox jumps over the lazy dog";
System.out.println(input);
input = input.replaceAll(".$", "");
System.out.println(input);

This prints:

The quick brown fox jumps over the lazy dog
The quick brown fox jumps over the lazy do

Note that in practice the substring option would be more efficient, and probably is what you would want to use in production. But regex can also handle this requirement.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
-1

Instead of getting the last character just get the last index

int last = s.length() - 1;

Modify like this

public static void noLast(String s){
    int last = s.length() - 1;
    System.out.println(s.substring(0,last));
Yash
  • 3,438
  • 2
  • 17
  • 33
-1

You can use substring method.

String str = "stackoverflow";
System.out.println(str.substring(0,str.length-1);

will print stackoverflo. Eliminating the last character.

Substring method takes in parameter the begin index and end index.

Brooklyn99
  • 987
  • 13
  • 24
Sameer
  • 11
  • 1
  • 6