Remove first and last character from a string

Asked

Viewed 9,910 times

0

I need to remove the first and last character from a variable String, tried to use substring for this, but is giving the following error:

String index out of range

And I’m not finding a way to do it, I’ve done it so far:

conteudoLote.replace("[", "(").replace("]",")").substring(1,(conteudoLote.length()-1))

Content of the variable:

((1,'SCAB17003066B','Suprimento com Defeito e com Resíduo','Lexmark International','60FBX00','Fraco',15),(1,'SCAB160632D9FRET','Vazio','Lexmark International','50FBX00',null,50), (1,'SCAB17003066B','Vazio','Lexmark International','60FBX00',null,null), (1,'SCAB1714435C2','Vazio','Lexmark International','50F0Z00',null,null))

Is there any way to remove the first and last character of a string?

  • And where is the string you want to remove?

  • Your code ran normal for me: https://ideone.com/Y388jZ

  • Are you sure conteudoLote is not a string with less than two characters?

  • Not my string conteudoLote has more than two characters, I will change my query with the contents of the variable

  • For me, it works, see here in ideone. Besides, this string of yours doesn’t have any [ or ].

  • If your idea is to produce a JSON, I would use .replace('(', '[').replace(')',']') instead of .replace("[", "(").replace("]",")").

  • @Victorstafusa what’s the difference between replaces

  • @R.Santos They are opposites. I exchange parentheses for brackets, while your brackets for brackets. I’m also using replace characters (with single quotes) instead of replace strings (with double quotes), which should perform a little better.

  • @Victorstafusa, yes the question of parenthesis exchange for brackets I noticed, is that actually my original string is already with brackets so I do the replace so, another thing I noticed and that the error actually occurred when I put the replace('Suprimento com Defeito e com Resíduo', 'Garantia').replace('Suprimento Bom e com Resíduo', 'Resíduo') could try adding this to your template code to see if the error occurs to you like this?

Show 4 more comments

3 answers

2

public static String removePrimeiroEUltimo(String x) {
    if (x == null) return null;
    if (x.length() <= 2) return "";
    return x.substring(1, x.length() - 1);
}
  • Actually, his string can be null or have less than 2 characters, so I see how to throw that exception

  • @Math Se is null would-be NullPointerException. I think his case is less than 2 characters.

  • hum truth....

  • Not my string contentLote has more than two characters, I will change my query with the contents of the variable

2

1


you can make a substring of the second character up to the penultimate, this way:

String stringCortada = stringOriginal.substring(1, stringOriginal.length()-1);  

Browser other questions tagged

You are not signed in. Login or sign up in order to post.