0% found this document useful (0 votes)
13 views23 pages

Java String Manipulation Programs

The document contains multiple Java programs that demonstrate various string manipulation techniques. These include counting characters, vowels, and consonants, checking for anagrams, finding subsets and permutations, identifying palindromes, and removing whitespace. Each program is accompanied by its output, showcasing the functionality of the code.

Uploaded by

Suresh Mano
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views23 pages

Java String Manipulation Programs

The document contains multiple Java programs that demonstrate various string manipulation techniques. These include counting characters, vowels, and consonants, checking for anagrams, finding subsets and permutations, identifying palindromes, and removing whitespace. Each program is accompanied by its output, showcasing the functionality of the code.

Uploaded by

Suresh Mano
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1) Java Program to count the total number of characters in a string

public class Practice {


public static void main(String[] args) {
String a = "Hi This is Dani";
int count = 0;
for (int i =0; i < [Link](); i++) {
if ([Link](i) != ' ')
count++;
}
[Link](count);
}
}
Output: 12

2) Java Program to count the total number of characters in a 2


strings:

3) Java Program to count the total number of punctuation characters


exists in a String
public class punctuation {
public static void main (String [] args) {
int countPuncMarks = 0;
String str = "Good Morning! Mr. James Potter. Had your
breakfast?";
for (int i = 0; i < [Link](); i++) {
if([Link](i) == '!' || [Link](i) == ',' || [Link](i) ==
';' || [Link](i) == '.' || [Link](i) == '?' || [Link](i) == '-' ||
[Link](i) == '\'' || [Link](i) == '\"' || [Link](i) == ':') {
countPuncMarks++;
}
}
[Link]("Total number of punctuation characters : "
+ countPuncMarks);
}
}

Output:
Total number of punctuation characters : 4

4) Java Program to count the total number of vowels and consonants


in a string:
public static void main(String[] args) {

int vCount = 0, cCount = 0;


String str = "This is a really simple sentence";

str = [Link]();

for(int i = 0; i < [Link](); i++) {


if([Link](i) == 'a' || [Link](i) == 'e' || [Link](i) ==
'i' || [Link](i) == 'o' || [Link](i) == 'u') {
vCount++;
}
else if([Link](i) >= 'a' && [Link](i)<='z') {
cCount++;
}
}
[Link]("Number of vowels: " + vCount);
[Link]("Number of consonants: " + cCount);
}
}

Output:
Number of vowels: 10
Number of consonants: 17
5) Java Program to determine whether two strings are the
anagram: ?

6) Java Program to divide a string in 'N' equal parts.

import [Link].*;
import [Link];
import [Link];

public class Sample {

static boolean areAnagram(char[] str1, char[] str2)


{
int n1 = [Link];
int n2 = [Link];

if (n1 != n2)
return false;

[Link](str1);
[Link](str2);
for (int i = 0; i < n1; i++)
if (str1[i] != str2[i])
return false;

return true;
}

public static void main(String args[])


{
char str1[] = { 'g', 'r', 'a', 'm' };
char str2[] = { 'a', 'r', 'm' };

if (areAnagram(str1, str2))
[Link]("The two strings are"
+ " anagram of each other");
else
[Link]("The two strings are not"
+ " anagram of each other");
}
}
Output:
The two strings are not anagram of each other

7) Java Program to find all subsets of a string:

public static void main(String[] args) {

String str = "FUN";


int len = [Link]();
int temp = 0;
String arr[] = new String[len*(len+1)/2];

for(int i = 0; i < len; i++) {


for(int j = i; j < len; j++) {
arr[temp] = [Link](i, j+1);
temp++;
}
}
[Link]("All subsets for given string are: ");
for(int i = 0; i < [Link]; i++) {
[Link](arr[i]);
}
}
}
Output:
F
FU
FUN
U
UN
N

8) Java Program to find the longest repeating sequence in a string:

public static String lcp(String s, String t){


int n = [Link]([Link](),[Link]());
for(int i = 0; i < n; i++){
if([Link](i) != [Link](i)){
return [Link](0,i);
}
}
return [Link](0,n);
}
public static void main(String[] args) {
String str = "acbdfghybdf";
String lrs="";
int n = [Link]();
for(int i = 0; i < n; i++){
for(int j = i+1; j < n; j++){
String x = lcp([Link](i,n),[Link](j,n));
if([Link]() > [Link]()) lrs=x;
}
}
[Link]("Longest repeating sequence: "+lrs);
}
}

Output:
Longest repeating sequence: bdf

9) Java Program to find all the permutations of a string:


public static void main(String[] args)
{
String str = "ABC";
int n = [Link]();
Permutation permutation = new Permutation();
[Link](str, 0, n-1);
}
private void permute(String str, int l, int r)
{
if (l == r)
[Link](str);
else
{
for (int i = l; i <= r; i++)
{
str = swap(str,l,i);
permute(str, l+1, r);
str = swap(str,l,i);
}
}
}
public String swap(String a, int i, int j)
{
char temp;
char[] charArray = [Link]();
temp = charArray[i] ;
charArray[i] = charArray[j];
charArray[j] = temp;
return [Link](charArray);
}

Output:
ABC
ACB
BAC
BCA
CBA
CAB

10) Java Program to remove all the white spaces from a string
public class removeWhiteSpace {
public static void main(String[] args) {

String str1="Welcome to Java";

//Removes the white spaces using regex


str1 = [Link]("\\s+", "");

[Link]("String after removing the white spaces : "


+ str1);
}
}
Output
------
String after removing the white spaces : WelcometoJava

11) Java Program to replace lower-case characters with upper-case


and vice-versa
Public class Sample{
public static void main(String[] args) {

String a = "java";
String a1 = [Link]();
[Link](a1);
}
}
Output
------
JAVA

public class Sample{


public static void main(String[] args) {

String a = "JAVA";
String a1 = [Link]();
[Link](a1);
}
}
Output
------
java

12) Java Program to replace the spaces of a string with a specific


character
public class Replace{
public static void main(String[] args) {

String a ="Welcome to Java";


String a1 = [Link](" ","$");
[Link](a1);
}
}

13) Java Program to determine whether a given string is palindrome

public class PalindromeString{


public static void main(String[] args) {
String a = "madam";
String a2 = "";
for(int i=[Link]()-1;i>=0;i--){
char ch = [Link](i);
a2= a2+ch;
}
[Link](a2);
if([Link](a2)) {
[Link]("Palindrome String");
}else {
[Link](" Not Palindrome String");
}
}}

14) Java Program to determine whether one string is a rotation of


another

15) Java Program to find maximum and minimum occurring


character in a string

16) Java Program to find Reverse of the string

public class Employee {


public static void main(String[] args) {
String name = "Welcome";
String res = "";
for (int i = [Link]() - 1; i >= 0; i--) {
char ch = [Link](i);
res = res + ch;
}
[Link](res);
}
}
Output : emocleW

17) Java program to find the duplicate characters in a string

18) Java program to find the duplicate words in a string

19) Java Program to find the frequency of characters


------------------------------------------------------------------
public class FrequencyOfChar {

public static void main(String[] args) {

String name = "Welcome";


Map<Character, Integer> emp = new
LinkedHashMap<>();
char[] ch = [Link]();
for (char c : ch) {
if ([Link](c)) {
int count = [Link](c);
[Link](c, count + 1);
} else {
[Link](c, 1);

}
[Link](emp);

20) Java Program to find the largest and smallest word in a string
-------------------------------------------------------------------------

public class LargestAndSmallestWordInTheString {

public static void main(String[] args){


String string = "AiiTE June Batch";
String word = "", small = "", large="";
String[] words = new String[100];
int length = 0;

string = string + " ";

for(int i = 0; i < [Link](); i++){

if([Link](i) != ' '){


word = word + [Link](i);
}
else{

words[length] = word;

length++;

word = "";
}
}
small = large = words[0];

for(int k = 0; k < length; k++){

if([Link]() > words[k].length())


small = words[k];

if([Link]() < words[k].length())


large = words[k];
}
[Link]("Smallest word: " + small);
[Link]("Largest word: " + large);
}
}

21) Java Program to find the most repeated word in a text file
------------------------------------------------------------------------------

22) Java Program to find the number of the words in the given text
file
------------------------------------------------------------------------------

23) Java Program to separate the Individual Characters from a String


------------------------------------------------------------------------------

public class SeparateChar {


public static void main(String[] args)
{

String string = " JAVA SELENIUM ";

[Link](
"Individual characters from given string: ");

for (int i = 0; i < [Link](); i++) {


[Link]([Link](i) + " ");
}
}
}

24) .
25) Java Program to print smallest and biggest possible palindrome
word in a given string
------------------------------------------------------------------------------------------------
------
public class largestAndSmallestPalindromeWordsInSentence
{
public static void main(String[] args)
{
String
sen="",wd="",wd1="",largestPalindrome="",smallestPalindrome="";
char ch=' ',ch1=' ';
int i=0,len=0;
Scanner sc = new Scanner([Link]);

[Link]("Enter a sentence");
sen = [Link]();
sen=sen+" ";
sen=[Link]();
len=[Link]();
smallestPalindrome=sen;
for(i=0;i< len;i++)
{
ch=[Link](i);
if(ch==' ')
{

if([Link](wd1)==true)
{
if([Link]()>[Link]())
{
largestPalindrome=wd;
}
if([Link]()< [Link]())
{
smallestPalindrome=wd;
}
}
wd1="";
wd="";
}
else
{
wd=wd+ch;
wd1=ch+wd1;
}
}
[Link]("Largest Palindrome words in
sentence:"+largestPalindrome);
[Link]("Smallest Palindrome words in
sentence:"+smallestPalindrome);

}
}
26) Reverse String in Java Word by Word
------------------------------------------------------------
public class ReverseStringWordByWordProgram
{
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Original string : ");

String originalStr = [Link]();


[Link]();

String words[] = [Link]("\\s");


String reversedString = "";

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


{
String word = words[i];
String reverseWord = "";
for (int j = [Link]() - 1; j >= 0; j--) {
reverseWord = reverseWord + [Link](j);
}
reversedString = reversedString + reverseWord + " ";
}

// Displaying the string after reverse


[Link]("Reversed string : " +
reversedString);
}
}

27) Reserve String without reverse() function.


-------------------------------------------------------
public class Employee {
public static void main(String[] args) {
String name = "Welcome";
String res = "";
for (int i = [Link]() - 1; i >= 0; i--) {
char ch = [Link](i);
res = res + ch;
}
[Link](res);
}
}

Common questions

Powered by AI

The logic is to use the 'replace' method of the String class, which substitutes all occurrences of spaces with the specified character. For multiple consecutive spaces, using 'replaceAll' with a regex can handle such cases by targeting any sequence of spaces, ensuring consistency in substitution .

This recursive method swaps characters at different positions by fixing one character at a time and calling itself to permute the remaining characters. Alternatives for efficiency could involve iterative permutations using a stack or generating permutations one at a time using an iterative binary flag approach, reducing recursive overhead .

To extract all subsets of a string in Java, you utilize nested loops to traverse starting and ending indices for each subset, storing substrings in an array. Potential issues include correctly handling string boundaries to avoid out-of-bounds errors and ensuring the result includes all subsets, not just those starting from a specific index, which involves checking all possible starting and ending positions .

You split the string into words and iterate to find the extremes in length. Preprocessing could involve removing punctuation using regex or manual character checks to ensure words are not affected by punctuation, leading to accurate size comparisons .

The method reverses the string and checks for equality with the original. Case sensitivity is addressed by converting the string to a uniform case, while spacing can be handled by removing non-alphanumeric characters before reversing. This ensures that trivial format differences do not affect palindrome detection .

To count vowels and consonants in a Java string, you iterate through each character, convert it to lowercase, and check if it's a vowel ('a', 'e', 'i', 'o', 'u'). For vowels, you increment a vowel counter, and for consonants (any alphabetic character that is not a vowel), you increment a consonant counter. Key considerations include handling non-alphabetic characters, ensuring case insensitivity, and correctly initializing and updating the counters. The provided program demonstrates how to count using specific 'if' conditions to identify vowels and consonants .

The method uses 'replaceAll' with the regex pattern '\s+' that matches all whitespace characters, not just spaces. This method effectively deletes different types of whitespace, including tabs and newlines, ensuring a clean, compact string .

The strategy involves iterating through the string and using a HashMap to store character-frequencies, where each character acts as a key and its occurrences as the value. This allows for efficient counting and retrieval due to the constant time complexity features of hash maps .

The approach involves creating a suffix for each character position, comparing pairs of suffixes to find the longest common prefix using a helper function, and tracking the maximum length found. This method can be optimized by recognizing only those comparisons between non-overlapping subsequences, thereby reducing unnecessary checks .

To determine if two strings are anagrams, the program first checks if their lengths are equal. If so, it converts the strings to character arrays, sorts them, and compares each character in the sorted arrays. If all characters match, the strings are anagrams; otherwise, they aren't. This method ensures the comparison is based on character frequency rather than order, a key trait of anagrams .

You might also like