Java: Replace a string "python" with "java" and "java" with "python" in a given string
Replace "python" with "java" and Vice Versa
Write a Java program to replace a string "python" with "java" and "java" with "python" in a given string.
Input:
English letters (including single byte alphanumeric characters, blanks, symbols) are given on one line. The length of the input character string is 1000 or less.
Visual Presentation:
Sample Solution:
Java Code:
// Importing necessary classes for input/output operations
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
// Main class named "Main"
class Main {
// Main method to execute the program
public static void main(String[] args) throws IOException {
// Creating BufferedReader object to read input from the user
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Prompting the user to input a string
System.out.println("Input the string:");
// Reading the input string
String str1 = br.readLine();
// Replacing occurrences of "java" with "py_thon"
str1 = str1.replaceAll("java", "py_thon");
// Replacing occurrences of "python" with "java"
str1 = str1.replaceAll("python", "java");
// Replacing occurrences of "py_thon" with "python"
str1 = str1.replaceAll("py_thon", "python");
// Outputting the new string
System.out.println("New string:");
System.out.println(str1);
}
}
Sample Output:
Input the string: python is more popular than java New string: java is more popular than python
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to swap occurrences of two given substrings in a sentence, carefully handling overlapping cases.
- Write a Java program to replace every occurrence of "python" with "java" in a large text file.
- Write a Java program to perform simultaneous substitution of two words in a string without using temporary storage.
- Write a Java program to interchange the positions of two specified words in a sentence while preserving all other text.
Go to:
PREV : Check Rectangle or Rhombus from Parallelogram Sides.
NEXT : Difference Between Largest and Smallest Integer.
Java Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.