KODNEST PRACTICE
P1:Write a java program to reverse the string by preserving the white spaces
package kodnest;
import [Link];
public class Reverse {
public static void main(String[] args) {
//creating a scanner object
Scanner scan =new Scanner([Link]);
//taking the input from the user
[Link]("Enter the string");
String str=[Link]();
//converting the string into character array
char arr1[]= [Link]();
// creating another array
char arr2[]=new char[[Link]];
[Link]("The string before reversing:"+str);
for(int i=0;i<=[Link]-1;i++)
{
if(arr1[i]==' ')
{
arr2[i]=' ';
}
}
// reversing the arr1 into arr2
int j=[Link]-1;
for(int i=0;i<=[Link]-1;i++)
{
if(arr1[i]!=' ')
{
if(arr2[j]==' ')
{
j--;
}
arr2[j]=arr1[i];
j--;
}
}
//converting arr2 into string and printing
str=new String(arr2);
[Link]("The reversed string is:"+str);
79
KODNEST PRACTICE
OUTPUT:
P2: Write a java program to reverse the string by each word
package kodnest;
import [Link];
public class Re_Verse {
public static void main(String[] args) {
Scanner scan =new Scanner([Link]);
//taking the input from the useer
[Link]("Enter the string");
String input=[Link]();
String revsent="";
//Splitting string where ever the space is preseent
String inputarr[]=[Link](" ");
//Reversing the each word and adding it to revsent
for(int i=0;i<=[Link]-1;i++)
{
String word=inputarr[i];
String revword=" ";
for(int j=[Link]()-1;j>=0;j--)
{
revword=revword+[Link](j);
}
revsent=revsent+revword;
}
//printing the reversed sentence
[Link](revsent);
}
80
KODNEST PRACTICE
OUTPUT:
Assignment
[Link](): returns a string that represent the character of the character
array
[Link]():Returns the formatted string using the specified local format string
and arguments
[Link](): Replaces the first occurrence of substring that matches the
given regular expression with the given replacement
[Link]():Returns the value of string object
[Link](): Removes whitespace from both ends of a string
[Link](): Returns the string representation of the specified value.
81