0% found this document useful (0 votes)
53 views

String Program

This document consists of a type of string program that would help computer science students learn and solve similar problems.

Uploaded by

Yogeshwara S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

String Program

This document consists of a type of string program that would help computer science students learn and solve similar problems.

Uploaded by

Yogeshwara S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

KODNEST PRACTICE

P1:Write a java program to reverse the string by preserving the white spaces
package kodnest;
import java.util.Scanner;
public class Reverse {

public static void main(String[] args) {


//creating a scanner object
Scanner scan =new Scanner(System.in);
//taking the input from the user
System.out.println("Enter the string");
String str=scan.nextLine();
//converting the string into character array
char arr1[]= str.toCharArray();
// creating another array
char arr2[]=new char[arr1.length];

System.out.println("The string before reversing:"+str);


for(int i=0;i<=arr1.length-1;i++)
{
if(arr1[i]==' ')
{
arr2[i]=' ';
}
}
// reversing the arr1 into arr2
int j=arr2.length-1;
for(int i=0;i<=arr1.length-1;i++)
{
if(arr1[i]!=' ')
{
if(arr2[j]==' ')
{
j--;
}
arr2[j]=arr1[i];
j--;
}
}
//converting arr2 into string and printing
str=new String(arr2);
System.out.println("The reversed string is:"+str);

79
KODNEST PRACTICE

OUTPUT:

P2: Write a java program to reverse the string by each word


package kodnest;
import java.util.Scanner;
public class Re_Verse {

public static void main(String[] args) {


Scanner scan =new Scanner(System.in);
//taking the input from the useer
System.out.println("Enter the string");
String input=scan.nextLine();
String revsent="";
//Splitting string where ever the space is preseent
String inputarr[]=input.split(" ");
//Reversing the each word and adding it to revsent
for(int i=0;i<=inputarr.length-1;i++)
{
String word=inputarr[i];
String revword=" ";
for(int j=word.length()-1;j>=0;j--)
{
revword=revword+word.charAt(j);
}
revsent=revsent+revword;
}
//printing the reversed sentence
System.out.println(revsent);
}

80
KODNEST PRACTICE

OUTPUT:

Assignment
1.copyValueOf(): returns a string that represent the character of the character
array
2.format():Returns the formatted string using the specified local format string
and arguments
3.replaceFirst(): Replaces the first occurrence of substring that matches the
given regular expression with the given replacement
4.toString():Returns the value of string object
5.trim(): Removes whitespace from both ends of a string
6.valueOf(): Returns the string representation of the specified value.

81

You might also like