Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete specific characters from a particular String in Java?

For example I'm extracting a text String from a text file and I need those words to form an array. However, when I do all that some words end with comma (,) or a full stop (.) or even have brackets attached to them (which is all perfectly normal).

What I want to do is to get rid of those characters. I've been trying to do that using those predefined String methods in Java but I just can't get around it.

like image 257
Slavisa Perisic Avatar asked Dec 25 '09 23:12

Slavisa Perisic


People also ask

How do you delete a certain character in a string?

Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.


2 Answers

Reassign the variable to a substring:

s = s.substring(0, s.length() - 1) 

Also an alternative way of solving your problem: you might also want to consider using a StringTokenizer to read the file and set the delimiters to be the characters you don't want to be part of words.

like image 170
Mark Byers Avatar answered Oct 09 '22 02:10

Mark Byers


Use:

String str = "whatever"; str = str.replaceAll("[,.]", ""); 

replaceAll takes a regular expression. This:

[,.] 

...looks for each comma and/or period.

like image 22
OMG Ponies Avatar answered Oct 09 '22 04:10

OMG Ponies