Replacing parts of a string - Java Language Basics

Java examples for Language Basics:String

Introduction

You can use the replaceFirst or replaceAll methods to replace a part of a string that matches a pattern.

Demo Code

import java.util.Scanner;

public class Main {

  public static void main(String[] args) {
    String s = "this is a cat";

    System.out.println(s);//w  w w.j a va2 s .co m

    s = s.replaceAll("cat", "dog");

    System.out.println(s);
  }

}

Related Tutorials