how to count an replace string in java

how to count an replace string in java

To count and replace a string in Java, you can use the replaceAll method of the String class.

The replaceAll method takes a regular expression and a replacement string as arguments, and returns a new string in which all occurrences of the regular expression are replaced with the replacement string.

Here is an example of how you can use the replaceAll method to count and replace a string in Java:

r‮efe‬r to:lautturi.com
String s = "Hello, world! Hello, world! Hello, world!";
String replaced = s.replaceAll("Hello", "Hi");
int count = s.length() - replaced.length();
System.out.println("Number of replacements: " + count);
System.out.println("Original string: " + s);
System.out.println("Replaced string: " + replaced);

This code defines a string called s with three occurrences of the string "Hello", and then uses the replaceAll method to replace all occurrences of "Hello" with "Hi". It stores the resulting string in a variable called replaced, and then calculates the number of replacements by subtracting the length of the replaced string from the length of the original string. Finally, it prints the number of replacements, the original string, and the replaced string to the console.

The output of this code will be:

Number of replacements: 3
Original string: Hello, world! Hello, world! Hello, world!
Replaced string: Hi, world! Hi, world! Hi, world!

Note that the replaceAll method takes a regular expression as the first argument, so you can use it to perform more advanced string replacements. For example, you can use a regular expression to match a specific pattern of characters and replace it with a different string.

If you only want to replace a specific string and not use a regular expression, you can use the replace method of the String class instead of the replaceAll method. The replace method takes two strings as arguments and replaces all occurrences of the first string with the second string.

Here is an example of how you can use the replace method to replace a specific string in Java:

public class Lautturi {
	public static void main(String[] args) {
		String s = "Hello, world! Hello, world! Hello, world!";
		String replaced = s.replace("Hello", "Hi");
		System.out.println(replaced);
	}
}

output:

Hi, world! Hi, world! Hi, world!
Created Time:2017-11-01 12:05:15  Author:lautturi