GroTechMinds

Strings Problems In Java

Introduction

String is one of the most important concepts in Java. Knowledge of String and its various methods is important for automation engineers to create better and more effective test scripts. Some of the string methods are concat()which joins two or more given strings, length() to find the length of the given string, trim() to remove the spaces in the beginning and ending  of the string and charAt() to find out the letter present at the index position of the String. Below are some of the string programs and their solutions which are important from an interview perspective.

Write a program to find out the length of the strings.
				
					 Ans. package stringproblems;
public class LengthOfString {
	public static void main(String[] args) {
		String a="Rahul";// Here we take a string with variable ”a” and name it as “Rahul”
		int length= a.length();// Using length method we are finding length of string. Since length is integer number we are taking int datatype.
		System.out.println(length);// So the length of the string is being printed here using this syntax.
	}
}

				
			

The below is the output for length of string

				
					Output: 5

				
			
Write a program to reverse a String.
				
					   Ans. package stringproblems;
public class StringReverse {
	public static void main(String[] args) {
		String input="Software"; // This is the string input which is taken to be reversed 
		String output=""; // The output of the string after getting reversed will be stored here and since the string is not yet reversed so it is taken as ""
		
	for(int i=input.length()-1;i>=0;i--) //For Loop is used to print all elements of string and in string reversal printing will start from last element and end in first element of string so the initial condition is taken as position or index of  last element of string and since indexing ends at position less than length of string so the last index is taken as length-1  and final condition is index of first element and it is taken as zero because indexing starts from zero.   
	{
		char reverse= input.charAt(i);// It is used for finding out characters at each index position in reverse order
	output=output+reverse; // For finding out the string in the reverse order
     		
	}
	
	System.out.println(output);// It will print the string in reverse order 
	}
	}

				
			

The below output shows the string printed in reverse order

				
					Output: erawtfoS
				
			
Write a program to check if two given strings are palindrome or not.
				
					Ans. package stringproblems;
public class Pallindrome {
	public static void main(String[] args) {
		String input="radar"; // Before checking if 2 strings are palindrome first we take 2 strings, reverse the strings and store them in separate variables output and output1 for input and input1 strings respectively. 
		String output="";
		String input1="ramesh";
		String output1="";
		for(int i=input.length()-1;i>=0;i--)// For Loop is used to print all elements of string and in string reversal printing will start from last element and end in first element of string so the initial condition is taken as position or index of  last element of string and since indexing ends at position less than length of string so the last index is taken as length-1  and final condition is index of first element and it is taken as zero because indexing starts from zero.  
		{
			char rev=input.charAt(i); // It is used for finding out characters at each index position in reverse order


			output=output+rev; // For finding out the string in the reverse order


		}
System.out.println(output); // It will print the string in reverse order 


if(input.equals(output)) //Using equals method of string concept we are comparing whether given string stored in ”input” variable is equal to its reversed string value stored in “output” variable.
{
	System.out.println("is a pallindrome");//If the string and its reverse are equal it will print this statement
}
else
{
	System.out.println("not a pallindrome"); //If the string and its reverse are not equal it will print this statement


}//The similar procedure we are following for “ramesh” string stored in “input1” variable and its reversed stored in “output1” variable.
for(int i=input1.length()-1;i>=0;i--)
		{
			char rev1=input1.charAt(i);
			output1=output1+rev1;
		}
System.out.println(output1);
if(input1.equals(output1))
{
	System.out.println("is a pallindrome");
}
else
{
	System.out.println("not a pallindrome");
}
	}
}

				
			

The given below is the output showing that “radar” is pallindrome but “ramesh” is not pallindrome

				
					Output: radar
       is a pallindrome
       hsemar
       not a pallindrome
				
			
Check in a given String which is a char value and which is a numeric value
				
					Ans.  String name="manish1";// We have taken a string as”manish1” and stored in “name” variable. 
		char name1[]= name.toCharArray();// We convert the given string into a char using tochararray method and store in “name1” variable because tochararray is array method and in string there is no array method. 
		 for(char i : name1)// here for each loop is used for complete iteration of the string after being converted to array.
		 {
		 boolean answer= Character.isDigit(i); //Here “Character” is final class and “isDigit” is method which is used to check the digits and letters present in that array and is stored in boolean return type since it will give true and false values.
		System.out.println(answer);// It prints the letters and digits present in the given string
	}

				
			

The below is the output showing number of characters and digits in the given string where the characters are given false output and digits as true since isDigit method is used.

				
					Output:   false
          false
          false
          false
          false
          false
true

				
			
Check in a given String how many are char value and how many are a numeric value
				
					Ans. package stringproblems;
public class StringNoOfCharAndDigits {
	public static void main(String[] args) {
		String name= "Rahul1234"; // String is declared, initialised and stored in “name” variable. 
		char c[]=name.toCharArray();// converting the string to character using “tochararray” method which returns char datatype.
		int count=0;// By default 2 counts,one for character and one for digit  with zero value for each count taken and stored in “count” and “temp” variables respectively.
		int temp=0;
		for(int i=0; i<name.length();i++) // for loop is used for easy finding of characters and digits in the string
		{
			boolean value=Character.isDigit(c[i]);// Here we are using “isDigit” method with “Character” as final class to display the digits and stored in”value” variable.
			if(value==true)// if the digits are present in each index of the string then it will print the number of digits through increment of “count” otherwise it will print number of characters through increment of “temp” as shown in below else block.
			{
				count++;
			}
			else
				temp++;
		}
System.out.println("The number of digits are:"+count );//To print the number of digits.
System.out.println("The number of characters are:"+temp);//To print the number of characters.
	}
}

				
			

The below output mentions the number of characters and digits present in the given string

				
					Output: The number of digits are:4
       The number of characters are:5

				
			
How do you check if a string contains only digits?
				
					Ans.  package stringproblems;
public class CheckingifStringHasonlyDigits {
	public static void main(String[] args) {
		int digit=0; // By default we have taken the count of digit and character as zero and stored them in “digit” and “charater” variable respectively.
		int charater=0;
	String name="123"; // a string consisting of numbers is taken and stored in name variable
	char name1[]=	name.toCharArray(); //string is converted to array using”tochararray” method
		for(char i : name1) //After converting string to array for each loop is used for complete iteration.
		{	
			boolean answer=	Character.isDigit(i);	// Here we are using “isDigit” method with “Character” as final class to display the digits and stored in”answer” variable.


		if(answer==true)// if the digits are present in each index of the string then it will print the number of digits through increment of “digit” otherwise it will print number of characters through increment of “charater” as shown in below else block.


		{
			digit++;
		}
		else
		{
			charater++;
		}
		
		}
		System.out.println("Numbers of numeric's in the given String are:"+digit);// for printing the number of digits present in the given string. 
		System.out.println("Numbers of characters in the given String are:"+charater); // for printing the number of characters present in the given string.
		if(name.length()==digit) //if length of string is equal to the number of digits then it will print the below statement		{
			System.out.println("Your String is just made up of Numeric value");
	}
		
	}
}

				
			

The below shows the output of the code snippet.

				
					Output: Numbers of numeric's in the given String are:3
Numbers of characters in the given String are:0
Your String is just made up of Numeric value

				
			
Write a program to find out if two strings are anagram of each other.
				
					Ans. package stringproblems;
import java.util.Arrays;
public class StringAnagram {
	public static void main(String[] args) {
		String first="vishnu"; // Two strings are taken using same letters of english alphabet
		String second="vishnu";
		
		if(first.length()!=second.length()) // if length of two strings are not equal it will print the below statement.
		{
			System.out.println("The 2 strings are not anagram of each other");
		}
		else 
		{  //In case the length of 2 strings are equal then we convert each string to  char array since there is no array method in string. 
			char input1[]=	first.toCharArray();
			char input2[]=	second.toCharArray();
			Arrays.sort(input1); // since anagram refers to two similar or different strings formed from same letters of english alphabet, to make steps for proving anagram easier after converting the 2 strings into arrays we sort the 2 arrays using Arrays.sort where “Arrays” is class and “sort” is method
			System.out.println(Arrays.toString(input1));//After sorting the 2 arrays we again convert those 2 arrays into string using “toString” method.
			Arrays.sort(input2);
			System.out.println(Arrays.toString(input2));
			if(	Arrays.equals(input1, input2)==true)//using if statement and equals method we check if 2 strings are formed from same letters or not.  
			{
			System.out.println("Anagram");//If two strings are formed from same letters then this statement will be printed
			}
			else 
			{
				System.out.println("Not an anagram");//If two strings are not formed from same letters then this statement will be printed


			}
		}
	}
}

				
			

The below is the output for above code snippet

				
					Output:    [h, i, n, s, u, v]
           [h, i, n, s, u, v]
           Anagram
				
			
Program to check if a given string contains space.
				
					 Ans. package stringproblems;
public class Space {
	public static void main(String[] args) {
		boolean s2=false; // first boolean value is declared and initialized as false so that in upcoming logic of program a statement will be printed that string contains space.
		String idea="Idea143 123"; //a string containing space is taken and stored in”idea” variable.
			char s1[]=	idea.toCharArray(); // string is converted to array using “tochararray” method since there is no string method to prove presence of space
			for(int i=0;i<idea.length();i++)// after converting string to array, for loop is used to detect presence of space in the array.
			{			
			 s2=	Character.isWhitespace(s1[i]); //space is checked in every index of array using “isWhitespace” method 
			
			if(s2==true) // if space is present then it will print below statement  
			{
				System.out.println("Hello space");
			}
	}
	}}

				
			

The below is the output of the given code snippet

				
					Output:  Hello space
				
			
Check if the given string has a special character in it.
				
					 Ans. package stringproblems;
public class StringhasSpecialCharacterornot {
	public static void main(String[] args) {
		boolean space=false;  // Initially space, alphabet and digit is taken as false  and returns boolean datatype and count of characters,digits and spaces taken as zero and returns as int datatype in order to print the  number of alphabets,digits and spaces present the given string in upcoming logic.  
		boolean alpha=false;
		boolean digit=false;
		int countofchar=0; 
		int countofdigit=0;
		int countofspace=0;
		String idea="Man@123^"; //String is taken containing numbers,letters and special characters.
		System.out.println("Given String is:->"+idea);// Given string is printed
			char s1[]=	idea.toCharArray();// after printing string is converted to array since there is no string method for detecting presence of space,alphabet and digit in string 
			for(int i=0;i<idea.length();i++) //for loop is used to check the presence of space in string 
			{			
				space=	Character.isWhitespace(s1[i]); // isWhitespace method is used to check presence of space
			alpha=Character.isAlphabetic(s1[i]); //isAlphabetic method is used to check presence of alphabet


			digit=Character.isDigit(s1[i]);//isDigit method is used to check presence of digit


			 if(space==true) //if space is present it will count the number of spaces 
			 {
				 countofspace++;
			 }
			 if(alpha==true) //if alphabet is present it will count the number of alphabets 


			 {
				 countofchar++;
			 }
			 if(digit==true) //if digit is present it will count the number of digits


			 {
				 countofdigit++;
			 }
			
			}
			 System.out.println("Space are->"+countofspace+" In the given String");//It will print the number of spaces present in the given string
				System.out.println("Characters are->"+countofchar +" In the given String"); //It will print the number of characters present in the given string


				System.out.println("Digits are->"+countofdigit+" In the given String");//It will print the number of digits present in the given string


				if(idea.length()!=(countofchar+countofspace+countofdigit))
				{ //if length of string is not equal to sum of number of characters,letters,and spaces of string then it will print below statement. 
					System.out.println("The given Sting has special character in it");
				}
				else
				{  //if length of string is equal to sum of number of characters,letters,and spaces of string then it will print below statement.
					System.out.println("No special character found");
				}
			
	}
} 

				
			

The below is the output of the given code snippet

				
					Output: Given String is:->Man@123^
        Space are->0 In the given String
        Characters are->3 In the given String
      Digits are->3 In the given String
      The given Sting has special character in it

				
			
Conclusion:

In short, solving string problems in Java may appear daunting at first, but with practice and understanding, you can master even the most complicated tasks. Learning string manipulation techniques and tactics provides you with an essential skill set that will help you in a variety of programming situations. Remember to practise consistently, look at real-life examples, and stay curious about new methods and functions that can help you improve your string manipulation skills. With dedication and determination, you can become an expert Java programmer able to solve any string-related problem with ease.

Upskill Yourself
Consult Us