Advertisements
Advertisements
प्रश्न
Write a program for the following.
Input a string from the user and also two characters. Find the first character in the word and then replace it with the second character and display the new word after replacement.
Example:
| Input: | |||
| Word | "CONSEQUENCES"; | C1 = 'E'; | C2 = 'O'; |
| Output | "CONSOQUONSOS" |
कोड लेखन
Advertisements
उत्तर
import java.util.*;
class clTask
{
void main()
{
String s1 = ', s2 = ', s3= "";
Scanner sc = new Scanner(System.in);
char oldch, newch, ch1, ch2;
int count = 0;
System.out.print(" Enter a sentence : ");
s1 = sc.nextLine();
System.out.print(" Enter old character: ");
oldch = sc.next().charAt(0);
System.out.print(" Enter new character : ");
newch = sc.next().charAt(0);
for(int j = 0; j<= s1.length() - 1; j++)
{
ch1 = s1.charAt(j);
if(ch1=oldch)
{
s2 = s2 + newch;
}
else
{
s2 = s2 + ch1;
}
}
System.out.println("New string is: " + s2);
}
}
Output:
Enter a sentence : CONSEQUENCES
Enter old character: E
Enter new character: O
New string is : CONSOQUONCOS
shaalaa.com
क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
अध्याय 10: String Handling - Exercises [पृष्ठ २४८]
