Java Program of String – Find and replace the character (First occurrence)

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:

  1. Array square
  2. Generate number using odd digits
  3. Alternate Number Difference
  4. Next Greatest number
  5. Mark Comparison
  6. Print the characters in descending order
  7. Vowels in a fishBowl
  8. Least offer
  9. Ascending and descending order
  10. Mail Domain
  11. Count repeating words
  12. Sentence – Convert to upper and lower
  13. Count consecutive repeating characters
  14. Zig zag Array
  15. Pass and Fail Count
  16. Search a Course
  17. Average and Grade Calculation
  18. String – Find and replace the character (first occurrence)
  19. Sort the first and second half of an array
  20. Retail Shop
  21. Palindrome
  22. Numerology
  23. InitCap
  24. Array Compatiblilty
  25. Sum of the maximum and the minimum element
  26. String Concatenation
  27. Find Average Age
  28. Login
  29.  

Leave a Comment

Your email address will not be published. Required fields are marked *

x