sirvon
sirvon

Reputation: 2625

Replace first occurrence of character in Android/Java?

I would like to take the 's' out of http.

 https://joy.tothewor.ld/today/and/tommorrow

 http://joy.tothewor.ld/today/and/tommorrow

What's the fastest/less expensive way?

substring, string builder, something newer in Android's SDK?

Upvotes: 6

Views: 6478

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136032

String.replaceFirst is heavyweight

 public String replaceFirst(String regex, String replacement) {
        return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
 }

this is the fastest way

str = str.substring(0, 4) + s.substring(5);

Upvotes: 4

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

You can try this

String str="https://joy.tothewor.ld/today/and/tommorrow"
                                            .replace("https://","http://");

Upvotes: 1

stinepike
stinepike

Reputation: 54682

String.replaceFirst will do the job.

String output = input.replaceFirst("s","");

Upvotes: 21

Related Questions