0% found this document useful (0 votes)
33 views25 pages

Java String Manipulation Programs

The document provides various Java programming exercises focused on string manipulation, including reversing strings, checking for palindromes, removing special characters, and counting vowels. Each exercise includes sample input and output, along with two different approaches to solve the problem. The document serves as a comprehensive guide for practicing string-related algorithms in Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views25 pages

Java String Manipulation Programs

The document provides various Java programming exercises focused on string manipulation, including reversing strings, checking for palindromes, removing special characters, and counting vowels. Each exercise includes sample input and output, along with two different approaches to solve the problem. The document serves as a comprehensive guide for practicing string-related algorithms in Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

String

1. Write a java program to display reverse of a string?

Input:
Hello
Output:
olleH

Approach1:

class ReverseStr
{
public static void main(String[] args)
{
String str=”Hello”;
char[] carr=[Link]();
String rev=””;
for(int i=[Link]-1;i>=0;i--)
{
rev+=carr[i];
}
[Link](rev);
}
}

Approach2:

class ReverseStr
{
public static void main(String[] args)
{
String str=”Hello”;
StringBuffer sb=new StringBuffer(str);
[Link]([Link]().toString());
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


2. Write a java program to check given string is palindrome or not?

Input:
racar
Output:
It is a palindrome string

Approach1:

class PalindromeApp
{
public static void main(String[] args)
{
String str=”racar”;
char[] carr=[Link]();
String rev=””;
for(int i=[Link]-1;i>=0;i--)
{
rev+=carr[i];
}
if([Link](rev))
[Link](“It is a palindrome string”);
else
[Link](“It is not a palindrome string”);
}
}

Approach2:

class PalindromeApp
{
public static void main(String[] args)
{
String str=”racar”;
StringBuffer sb=new StringBuffer(str);
String rev=[Link]().toString();
if([Link](rev))
[Link](“It is a palindrome string”);
else
[Link](“It is not a palindrome string”);

}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


3. Write a java program to display reverse of a sentence?

Input:
This is java class
Output:
class java is This

class ReverseSentence
{
public static void main(String[] args)
{
String str="This is java class";
String[] sarr=[Link](" ");
String rev=””;
for(int i=[Link]-1;i>=0;i--)
{
rev+=sarr[i]+” “;
}
[Link](rev);
}
}

4. Write a java program to remove special characters from given string?

Input:
he@l#l_o$
Output:
hello

class RemoveCharacter
{
public static void main(String[] args)
{
String str="he@l#l_o$";

str=[Link]("[^a-zA-Z0-9]","");

[Link](str);
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


5. Write a java program to display reverse of each word in a sentence?

Input:
This is java class
Output:
sihT si avaj sslac

class ReverseWord
{
public static void main(String[] args)
{
String str="This Is Java Class";
String[] sarr=[Link](" ");
for(String s:sarr)
{
char[] carr=[Link](); // T h i s
//reverse order
for(int i=[Link]-1;i>=0;i--)
{
[Link](carr[i]);
}
//space
[Link](" ");
}
}
}

6. Write a java program to remove spaces from given string?

Input:
I HUB Tal ent
Output:
IHUBTalent

class RemoveSpaces
{
public static void main(String[] args)
{
String str="I HUB Tal ent";
str=[Link]("\\s","");
[Link](str);
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


7. Write a java program to display duplicate characters in a given string?

Input:
google

Output:
og

class DuplicateCharacters
{
public static void main(String[] args)
{
String str="google";
String characters="";
String duplicates="";
for(int i=0;i<[Link]();i++)
{
//converting character to String
String current=[Link]([Link](i));
if([Link](current))
{
if(![Link](current))
{
duplicates+=current;
continue;
}
}
characters+=current;
}
[Link](duplicates);
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


8. Write a java program to display unique characters in a given string?

Input:
google

Output:
gole

class UniqueCharacters
{
public static void main(String[] args)
{
String str="google";

String characters="";
String duplicates="";

for(int i=0;i<[Link]();i++)
{
//converting character to String
String current=[Link]([Link](i));

if([Link](current))
{
if(![Link](current))
{
duplicates+=current;
continue;
}
}
characters+=current;
}
[Link](characters);
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


9. Write a java program to check given string is anagram or not?

Input:
silent
listen
Output:
It is Anagram string

import [Link];
class Test
{
public static void main(String[] args)
{
String str1="silent";
String str2="listen1";

//convert string to char array


char[] ch1=[Link]();
char[] ch2=[Link]();

//sorting the characters


[Link](ch1);
[Link](ch2);

boolean flag=true;
for(int i=0;i<[Link];i++)
{
if(ch1[i]!=ch2[i])
{
flag=false;
break;
}
}
if(flag)
[Link]("It is Anagram String");
else
[Link]("It is not Anagram String");
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


10. Write a java program to display the string in a given format?

Input:
A1B2C3D4

Output:
ABBCCCDDDD

class StringFormat
{
public static void main(String[] args)
{
String str="A1B2C3D4";

for(int i=0;i<[Link]();i++)
{
if([Link]([Link](i)))
{
[Link]([Link](i));
}
else
{
int k=[Link]([Link](i));

for(int j=1;j<k;j++)
{
[Link]([Link](i-1));
}
}

}
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


11. Write a java program to display the string in a given format?

Input:
XYZ

Output:
XY
XZ
YX
YZ
ZX
ZY

class StringFormat
{
public static void main(String[] args)
{
String str="XYZ";

for(int i=0;i<[Link]();i++)
{
for(int j=0;j<[Link]();j++)
{
if(i!=j)
{
[Link]([Link](i)+""+[Link](j));
}
}
}
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


12. Write a java program to permutation of a given string?

Input:
ABC

Output:
ABC
ACB
BAC
BCA
CBA
CAB

class PermutationString
{
public static void main(String[] args)
{
String str="ABC";
//caller method
permutation([Link](),0);
}
//callie method
public static void permutation(char[] arr,int fi)
{
if(fi==[Link]-1)
{
[Link](arr);
return;
}
for(int i=fi;i<[Link];i++)
{
swap(arr,fi,i);
permutation(arr,fi+1);
swap(arr,fi,i);
}
}
//callie method
public static void swap(char[] arr,int fi,int i)
{
char temp=arr[fi];
arr[fi]=arr[i];
arr[i]=temp;
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


13. Write a java program to display the string in a given format?

Input:
ABBCCCDDDD

Output:
A1B2C3D4

class Test
{
public static void main(String[] args)
{
String str="ABBCCCDDDD";

StringBuffer sb=new StringBuffer();

int count=1;

for(int i=0;i<[Link]();i++)
{
if(i<[Link]()-1 && [Link](i)==[Link](i+1))
{
count++;
}
else
{
[Link]([Link](i)).append(count);
count=1;
}
}
[Link]([Link]());
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


14. Write a java program to concatenate two strings?

Input:
ihub23
talent24

Output:
ihubtalent47

class ConcatinateTwoStrings
{
public static void main(String[] args)
{
String str1="ihub23";
String str2="talent24";

String word1=[Link]("[^A-Za-z]","");
int num1=[Link]([Link]("[^0-9]",""));

String word2=[Link]("[^A-Za-z]","");
int num2=[Link]([Link]("[^0-9]",""));

String word=word1+word2;
int num=num1+num2;

[Link](word+num);

}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


15. Write a java program to insert a given word using index number?

Input:
str = "ihubtalentIT"

index = 4

word = "for"

Output:
ihubfortalentIT

class WordInsertApp
{
public static void main(String[] args)
{
String str="ihubtalentIT";

int index=4;

String word="for";

String str1=[Link](0,index);
String str2=[Link](index,[Link]());

String result=str1+word+str2;

[Link](result);

}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


16. Write a java program to display the string starting with uppercase letters?

Input:
This is Java class For students

Output:
This Java For

class UpperCaseString
{
public static void main(String[] args)
{
String str="This is Java class For students";

String[] sarr=[Link](" ");

for(String s:sarr)
{
if([Link](0)>='A' && [Link](0)<='Z')
{
[Link](s+" ");
}
}
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


17. Write a java program to display number of words present in String?

Input:
This is is java java class

Output:
This=1, is=2, java=2, class=1

import [Link].*;
class NumberOfWords
{
public static void main(String[] args)
{
String str="This is is java java class";

String[] sarr=[Link](" ");

Map<String,Integer> map=new LinkedHashMap<String,Integer>();

for(String s:sarr)
{
if([Link](s)!=null)
{
[Link](s,[Link](s)+1);
}
else
{
[Link](s,1);
}
}
[Link]((key,value)-> [Link](key+”=”+value));
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


18. Write a java program to display number of characters present in string?

input:
java

output:
j=1,a=2,v=1

import [Link].*;
class NumberOfCharacters
{
public static void main(String[] args)
{
String str="java";

char[] carr=[Link]();

Map<Character,Integer> map=new LinkedHashMap<Character,Integer>();

for(char c:carr)
{
if([Link](c)!=null)
{
[Link](c,[Link](c)+1);
}
else
{
[Link](c,1);
}
}
[Link]((key,value)-> [Link](key+”=”+value));
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


19. Write a java program to check given string is balanced or not?

Input:
[{()}]
Output:
It is balanced string

import [Link].*;
class BalancedString
{
public static void main(String[] args)
{
String str="[{()}]";
if(isBalanced([Link]()))
[Link]("It is balanced string");
else
[Link]("It is not balanced string");
}
public static boolean isBalanced(char[] carr)
{
Stack<Character> s=new Stack<Character>();
for(char ch:carr)
{
if(ch=='[' || ch=='{' || ch=='('){
[Link](ch);
}
else if(ch==']' && ![Link]() && [Link]()=='['){
[Link]();
}
else if(ch=='}' && ![Link]() && [Link]()=='{'){
[Link]();
}
else if(ch==')' && ![Link]() && [Link]()=='('){
[Link]();
}
else{
return false;
}
}

return [Link]();
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


20. Write a java program to count number of vowels present in a given string?

Input:
Umbrella
Output:
3

class VowelCounter
{
public static void main(String[] args)
{
String str="umbrella";
str=[Link]();
int count = 0;
for (int i = 0; i < [Link](); i++)
{
char ch = [Link](i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
{
count++;
}
}
[Link](count);
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


21. Write a java program to perform right rotation of a given string?

Input:
str= “Ihubtalent”
position = 4
Output:
talentihub

class RightRotation
{
public static void main(String[] args)
{
String str="ihubtalent";
int position=4;

String str1=[Link](position,[Link]());
String str2=[Link](0,position);

[Link](str1+str2);
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


22. Write a java program that takes list of string and display them in sorting order?

Input:
Hello World My Name Is
Output:
Hello Is My Name World

import [Link].*;
public class SortingOrder
{
public static void main(String[] args)
{
String string="Hello World My Name Is";

String[] sarr=[Link](" ");

List<String> input = [Link](sarr);

[Link](input);

for (String str: input)


{
[Link](str + " ");
}
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


23. Write a java program to remove the given string?

Input:
str = “This is java program”
remove = “is”

Output:
Th java program

public class Test


{
public static void main(String[] args)
{
String str = "This is java program";
String remove = "is";

str=[Link](remove, "");

[Link](str);
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


24. Write a java program to perform encoding the string?

Input:
1106
Output:
AAJF

public class Test


{
public static void main(String[] args)
{
String input = "1106";
String encodedString = encodeString(input);
[Link]("Encoded String: " + encodedString);
}

public static String encodeString(String input)


{
StringBuilder sb = new StringBuilder();

for(int i=0;i<[Link]();i++) //1 1 0 6


{
String str=[Link]([Link](i));
int n=[Link](str);
if(n!=0)
{
[Link]((char) ('A' + n - 1));
}
else
{
String substr=[Link](i-1,i+1);
int digit=[Link](substr);
[Link]((char) ('A' + digit - 1));
}
}
return [Link]();
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


25. Write a java program to perform largest common subsequence in a given string?

Input:
ABCAB
AECB
Output:
3

class Test
{
public static void main(String[] args)
{
String firstStr="ABCAB";
String secondStr="AECB";

//caller
[Link](longestCommonSubsequence(firstStr,secondStr));
}
public static int longestCommonSubsequence(String s1,String s2)
{
return solve(s1,s2,0,0);
}
public static int solve(String str1,String str2,int i,int j)
{
if(i==[Link]())
return 0;
if(j==[Link]())
return 0;

int ans=0;
if([Link](i)==[Link](j))
{
ans=1+solve(str1,str2,i+1,j+1);
}
else
{
ans=[Link](solve(str1,str2,i+1,j),solve(str1,str2,i,j+1));
}

return ans;
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


26. Write a java program to display all palindrome strings?

Input:
racar is madam for dad
Output:
racar madam dad

import [Link].*;
public class Test
{
public static void main(String[] args)
{
String str="racar is madam for dad";
String[] sarr=[Link](" ");

for(String s:sarr)
{
char[] carr=[Link]();

String rev="";

for(int i=[Link]-1;i>=0;i--)
{
rev+=carr[i];
}
if([Link](rev))
[Link](s+" ");
}
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN


27. Write a java program to check number of uppercase letters, lowercase letters, digits and
special symbols?

Input:
This Is Java Class32
Output:
Uppercase letters: 4
Lowercase letters: 11
Digits: 2
Words: 4
Spaces: 3

public class Test


{
public static void main(String[] args)
{
String str="This Is Java Class32";

int upper=0,lower=0,digit=0,word=1,space=0;

for(int i=0;i<[Link]();i++)
{
if([Link](i)>='A' && [Link](i)<='Z')
upper++;
else if([Link](i)>='a' && [Link](i)<='z')
lower++;
else if([Link](i)>='0' && [Link](i)<='9')
digit++;
else if([Link](i)==' ')
{
space++;
word++;
}
}
[Link]("Uppercase letter :"+upper);
[Link]("Lowercase letter :"+lower);
[Link]("Digit :"+digit);
[Link]("Word :"+word);
[Link]("Spaces :"+space);
}
}

IHUB TALENT MANAGEMENT NIYAZ UL HASAN

Common questions

Powered by AI

There are two approaches mentioned in the document to reverse a string in Java. The first approach uses a loop to iterate through the input string from the end to the beginning, creating a reverse string by appending each character to a new string variable . The second approach leverages the 'StringBuffer' class, which provides a method 'reverse()', to directly reverse the string. This method internally uses a sequence of operations to reverse the sequence of characters in place, making it a more efficient solution in terms of performance .

The method to reverse the words in a sentence involves splitting the sentence into individual words based on spaces, storing them in an array, then iterating over this array in reverse order to construct the output where words appear in reverse order compared to the original sentence . This approach employs the 'split' method for breaking the sentence into words and a concatenation loop to reorder them .

To handle uniqueness of characters in a string, the Java approach involves iterating through the characters, maintaining two strings: one to capture all characters seen ('characters') and another to note duplicates ('duplicates'). For each character, it checks if it is in 'characters'; if not, the character is added. If it is, the character is added to 'duplicates' if it isn't already there, effectively tracking non-unique characters . This ensures only unique characters are initially captured .

The algorithm for converting a numeric string to an encoded alphabetical representation involves iterating through each character of the string, converting it to an integer, and mapping it to a letter using ASCII values ('A' + n - 1). If a digit other than zero is encountered, it's directly converted to a letter. When zero appears, the previous character and zero form a two-digit number, which is then converted to a corresponding letter . This logic uses ASCII calculations to encode numbers into letters .

The right rotation of a string as described in the document involves calculating the effective rotation point, then splitting the string into two substrings at this point. The second substring, from the calculated position to the end, is taken first, and the first part, from the start of the string to this point, is appended after it. This operation effectively rotates the string clockwise by the specified positions . This method efficiently reorganizes string parts to achieve rotation .

The document outlines a technique for identifying duplicate characters in a string using a Java program. The method involves initializing two strings, one for storing characters already seen and another for tracking duplicates. The program iterates through each character in the input string, converting it to a string to check its presence in the 'characters' string. If a character is already present, it is added to the 'duplicates' string if not already there . This process uses nested conditional checks to efficiently identify duplicates .

The document describes that an anagram check can be performed by first converting both strings into character arrays. The characters within these arrays are then sorted. A simple comparison is performed post-sorting to check if the sorted arrays are identical. If they are, it indicates that the strings are anagrams since they contain the same characters in the same frequency . This approach leverages both sorting and element-by-element comparison for validation .

The implementation counts various character types by iterating over each character in the string and checking its type using conditional structures. It uses 'if' statements to determine if a character is an uppercase, lowercase, or digit and maintains separate counters for each type. Additionally, it tracks spaces to count words, incrementing a word counter each time a space is encountered, ensuring the total word count is accurate . This routine relies on ASCII value range checks to differentiate characater types .

To determine if a string is a palindrome in Java, one can employ two approaches as described in the document. First, similar to string reversal, one can iterate through the string backwards, build a reversed copy of it, and finally compare the reversed string with the original. If they are identical, the string is a palindrome . The second approach makes use of 'StringBuffer' to reverse the string and then compares the reversed string with the original string using the 'equals' method .

The document explains a technique for checking if brackets in a string are balanced using a stack data structure. As the algorithm processes each character, if it encounters an opening bracket ('[', '{', '('), it pushes it onto the stack. For closing brackets (']', '}', ')'), it checks if the stack is not empty and if the top element matches the corresponding opening bracket, then pops it. If any of these conditions fail, the string is unbalanced. After processing, if the stack is empty, the brackets are balanced; otherwise, they are not . This method uses the stack's LIFO nature to efficiently match corresponding brackets .

You might also like