Question:
Write a Java program to find a character from a sentence and replace it with another character. If the character is not found in the string print “character not found”.
Note: Replace only the first occurrence.
Sample input 1:
Enter the string:
java programming
Enter the character to be searched:
a
Enter the character to replace:
o
Sample output 1:
jova programming
Sample input 2:
Enter the string:
java programming
Enter the character to be searched:
e
Enter the character to replace:
o
Sample output 2:
character not found
Code:
FirstOccurence.java
import java.util.*; public class FirstOccurence { public static void main (String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter the string:"); char[] str=sc.nextLine().toCharArray(); System.out.println("Enter the character to be searched:"); char srch=sc.next().charAt(0); System.out.println("Enter the character to replace:"); char replace=sc.next().charAt(0); int flag=0; int len=str.length; for(int i=0;i<len;i++) {char r=str[i]; if(r==srch) { str[i]=replace; flag++; break; } } if(flag==0) { System.out.println("character not found"); } else { for(char i : str) { System.out.print(i); } } } }
Recommended:
- Array square
- Generate number using odd digits
- Alternate Number Difference
- Next Greatest number
- Mark Comparison
- Print the characters in descending order
- Vowels in a fishBowl
- Least offer
- Ascending and descending order
- Mail Domain
- Count repeating words
- Sentence – Convert to upper and lower
- Count consecutive repeating characters
- Zig zag Array
- Pass and Fail Count
- Search a Course
- Average and Grade Calculation
- String – Find and replace the character (first occurrence)
- Sort the first and second half of an array
- Retail Shop
- Palindrome
- Numerology
- InitCap
- Array Compatiblilty
- Sum of the maximum and the minimum element
- String Concatenation
- Find Average Age
- Login