Programming Session 5#Playing with Strings
Reversing a String
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the String to be reversed");
String a=input.nextLine();
StringBuffer neew=new StringBuffer(a);
neew.reverse();//usage of reverse function by using objects from StringBuffer class
System.out.println("The reversed String is"+neew);
}
}
Replacing Something and Removal of White Space
import java.util.*;
public class Main
{
public static void main(String[] args)
{ System.out.println("Enter the String");
Scanner input = new Scanner(System.in);
String a=input.nextLine();
String b=a.replaceAll("\\s+","");//"\\s" is for white space.
String c=a.replaceAll("\\s","-");//note instead of \\s u can use any thing.
System.out.println(b);
System.out.println(c);
}
}
Mixing them both.
import java.util.*;
public class Main
{
public static void main(String[] args)
{ System.out.println("Enter the String");
Scanner input = new Scanner(System.in);
String a=input.nextLine();
String b=a.replaceAll("\\s+","");
String c=a.replaceAll("\\s","-");
StringBuffer d=new StringBuffer(b);
d.reverse();
StringBuffer e=new StringBuffer(c);
e.reverse();
System.out.println(d);
System.out.println(e);
}
}
posted by lol ik.
Comments
Post a Comment