William Stackler
William Stackler

Reputation: 3

Removing the last character from a string

I am having trouble with a recent Java project. I am attempting to just the String "white" from the String. No matter what method I attempt, the last "_" always remains.

    String questionText = "The white house is _white_";
    String correctResponse = questionText.replace(questionText.substring(0, questionText.indexOf("_")+1), "");
    correctResponse.substring(0,correctResponse.length()-1);
    System.out.println(correctResponse);

Upvotes: 0

Views: 93

Answers (7)

René Link
René Link

Reputation: 51323

If you use a regular expression you don't have to check index bounaries.

String string = "Merry Christmas!".replaceAll(".$", "");
System.out.println(string);

will print out

Merry Christmas

Upvotes: 0

Chamara Maduranga
Chamara Maduranga

Reputation: 256

You just need to change line 3.

Original Line : correctResponse.substring(0,correctResponse.length()-1);

Correct Line : correctResponse = correctResponse.substring(0,correctResponse.length()-1);

Upvotes: 0

agim
agim

Reputation: 1841

You think to complicated - why do you need replace? You can achieve the same with substring

First statement

String correctResponse = questionText.substring(questionText.indexOf("_")+1)
// ==> correctResponse = "white_"

Second statement

correctResponse = correctResponse.substring(0, correctResponse.indexOf("_"))
// ==> correctResponse = "white"

As @neuo pointed out, substring won't change the string..

Upvotes: 0

dukr
dukr

Reputation: 26

If the string you want is always between underscores (or at least after one underscore), you could just split the string and take the substring at index 1:

String correctResponse = questionText.split("_")[1];

Upvotes: 0

neuo
neuo

Reputation: 733

substring don't modify original object.

use

 correctResponse = correctResponse.substring(0, correctResponse.length() - 1);

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201399

I would use a regular expression to group everything between underscores, and then String.replaceAll(String, String) to actually remove everything but the group. Like,

String correctResponse = questionText.replaceAll(".+\\s+_(.+)_", "$1"); // white

Upvotes: 1

ThomasEdwin
ThomasEdwin

Reputation: 2145

Use lastIndexOf

String correctResponse = questionText.replace(questionText.substring(questionText.indexOf("_"), questionText.lastIndexOf("_")+1), "");

Upvotes: 0

Related Questions