Let's have some challenges!!
1. WAP in JAVA to remove all the space from the string.
2. Also, Make a separate program to remove all vowels from the string.
Restriction:
• You cannot use any Conditional statements like if else, ternary etc.
• No loopings
Answers
Solution to question 1.
import java.util.*;
public class RemoveSpaces{
public static void main(){
Scanner _=new Scanner(System.in);
System.out.print("Enter a string: ");
String s=_.nextLine().replace(" ","");
_.close();
System.out.println("The new string after removal of spaces is: "+s);
}
}
Solution to question 2.
import java.util.*;
public class RemoveVowels{
public static void main(){
Scanner _=new Scanner(System.in);
System.out.print("Enter a string: ");
String s=_.nextLine().replaceAll("[AEIOUaeiou]","");
_.close();
System.out.println("The new string after removal of vowels is: "+s);
}
}
The above questions are solved using the methods listed below -
- replace() - Searches for a specific string and replace them with another string.
- replaceAll() - It searches for pattern in a string and replaces with another string. Here, I wrote - "[AEIOUaeiou]". This means if any of the characters inside [ and ] is found, then it is deleted.
- No conditional statements used.
- No loop used.
See the attachment for output.
Answer:
Program:-
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
String st,st1,st2;
System.out.println("Enter a String");
st=in.nextLine();
st1=st.replace(" ","");
System.out.println("The new string after replacing spaces="+st1);
st2=st.replaceAll("[AEIOUaeiou]","");
System.out.println("The new string after replacing vowels="+st2);
}
}
Use of library methods:-
- The replace(a,b) method is used to replace the entered first character(inside method) and to replace the entered second character (inside method).
So, simply replace " " with "".
- The replaceAll([a],b) method is used to replace all the characters if it is found in the string.
So, simply replace "[AEIOUaeiou]" with"".
Note:-Don't place ',' inside the square brackets otherwise it will give an error.
Hope it helps...