stackyyflow
stackyyflow

Reputation: 763

String replace method is not working in android studio

I'm not too sure why my word doesn't get replaced in android studio.

    private Calendar dateTime = Calendar.getInstance();
    private SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy, EEE");
    String dateFormat = dateFormatter.format(dateTime.getTime());
    Button beginDate = (Button) findViewById(R.id.startDate);
    beginDate.setText("From     " + dateFormat);

    // Other codes removed for simplicity

    String beginD = beginDate.getText().toString().replace("From:     ", "");
    Log.d("Test", beginD); 

Log result as follows:

06-16 14:14:01.957 23893-23893/packagename D/Test﹕ From
16/06/2015, Tue

Upvotes: 1

Views: 3391

Answers (3)

Jens
Jens

Reputation: 69440

In your button text is no :. So you have to change the text of the botton to :

beginDate.setText("From:     " + dateFormat);

or your regex to

String beginD = beginDate.getText().toString().replace("From     ", "");

Upvotes: 1

Maroun
Maroun

Reputation: 95968

I don't see : in the input you entered, so From: won't be matched. I recommend using more generic pattern:

replaceAll("From:?\\s+", "");

Since replaceAll takes a regex, you can ask for optional :, followed by one or more space(s).

Upvotes: 3

Ted Hopp
Ted Hopp

Reputation: 234795

You're trying to replace "From: " but you only added "From " (without the :).

Upvotes: 7

Related Questions