String Handling Programs
- Categories Strings in Java, Java, String, String
1 . Write a program to get input a string from user and print number of vowels present in string.
import java.util.Scanner;
public class countVowels
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int vowels=0, consonant=0;
System.out.println("Enter a character : ");
String str =sc.next( );
for(int i=0; i<str.length();i++)
{
char c = str.charAt(i);
if ( (c >= 'a' && c <= 'z') ||(c >= 'A' && c <= 'Z') ) {
c = Character.toLowerCase(c);;
if (c == 'a' || c == 'e' || c == 'i' ||c == 'o' || c == 'u')
vowels++;
else
consonant++;
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonant: " + consonant);
}
}
2 . Write a program to get input a string from user and print number of uppercase and lowercase character present in string.
import java.util.Scanner;
public class countUpper
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int upper=0, lower=0, other=0;
System.out.println("Enter a character : ");
String str =sc.next( );
for(int i=0; i<str.length();i++)
{
char c = str.charAt(i);
if ( Character.isUpperCase(c) )
upper++;
else if (Character.isLowerCase(c))
lower++;
else
other++;
}
System.out.println("upper: " + upper);
System.out.println("lower: " + lower);
System.out.println("other: " + other);
}
}
3 . Write a program to get input a string from user and print Count how many times latter appears in a string.
import java.util.Scanner;
public class HowManyTimesLetterAppears
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int count=0;
System.out.println("Enter a string : ");
String str =sc.next( );
System.out.println("Enter a letter to check : ");
char SameChar= sc.next().charAt(0);
for(int i=0; i<str.length();i++)
{
char c = str.charAt(i);
if ( str.charAt(i) == SameChar)
count++;
}
System.out.println("Letter "+SameChar+" appears " + count+" times in string");
}
}
4 . Write a program to get input a string from user and print every letter with its ASCII Code in new line
import java.util.Scanner;
public class GivenStringToASCII
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a string : ");
String str =sc.next( );
for(int i=0; i<str.length();i++)
{
char c = str.charAt(i);
int asciiVal = c;
System.out.println(c+":"+asciiVal);
}
}
}
5 . Write a program to get input a string from user and swap case of a string.
import java.util.Scanner;
public class swapCase
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String str1="", str2="";
System.out.println("Enter a string : ");
str1 =sc.next( );
for (int i = 0; i < str1.length();i++)
{
char c = str1.charAt(i);
if(Character.isUpperCase(c))
str2 += Character.toLowerCase(c);
else if (Character.isLowerCase(c))
str2 += Character.toUpperCase(c);
else
str2 += c;
}
System.out.println("Swap String = "+ str2);
}
}
6 . Write a program to get input a string from user and Print a new string with each letter incremented by 2characters. Like A will become C.
import java.util.Scanner;
public class letterIncrementedBy2
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a string : ");
String str =sc.next( );
for(int i=0; i<str.length();i++)
{
char c = str.charAt(i);
int asciiVal = c+2;
System.out.println(c+":"+(char)asciiVal);
}
}
}
7 . Write a program to get input a string from user and Print the frequency of each character
import java.util.Scanner;
public class frequencyEachCharacter
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int allpha=256;
int count[] = new int[allpha];
System.out.println("Enter a string : ");
String str =sc.nextLine( );
for(int i=0; i<str.length();i++)
{
count[(int) str.charAt(i)]++;
}
for (int i = 0; i < 256; i++) {
if (count[i] != 0)
System.out.println((char) i + " occurred for: " + count[i]);
}
}
}
8 . Write a program to get input a string from user and Count no of words in a string and print each word in separate line.
import java.util.Scanner;
public class countWord
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a character : ");
String str =sc.nextLine( );
int count=0;
char c[]= new char[str.length()];
for(int i=0; i<str.length();i++)
{
c[i] = str.charAt(i);
if( ( (i>0)&& (str.charAt(i)!=' ') &&(str.charAt(i-1)==' ')) || ((str.charAt(i)!=' ')&&(i==0)) )
count++;
}
System.out.println("words: " + count);
}
}
9 . Write a program to get input a string from user and arrange each word in Alphabetical Order.
import java.util.*; public class AlphabeticalOrder { private int x; String str;
public AlphabeticalOrder()
{
x = 0;
}
public void readInput()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter string");
str = in.nextLine();
}
public void arrangeString()
{
char ch;
for(int i = 65; i<= 90;i ++)
{
for (int j = 0; j < str.length();j++)
{
ch = str.charAt(j);
if (ch == (char)i || ch == (char)(i+32))
{
System.out.print(ch);
}
}
}
}
public static void main (String [] args)
{
AlphabeticalOrder AO = new AlphabeticalOrder();
AO.readInput();
AO.arrangeString();
}
}
10 . Write a program to get input a string from user and Count no of words in a string and print each word in separate line.
import java.util.Scanner;
import java.io.*;
public class countWordOccurs
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a character : ");
String str =sc.nextLine( );
String word= "the";
int count=0;
for(int i=0; i<str.length();i++)
{
if(str.contains(word)){
count+=1;
i+=word.length()-1;
}
}
System.out.println("words: " + count);
}
}
11 . Write a program to get input a string from user and Count no of words in a string and print each word in separate line.
import java.util.Scanner;
import java.io.*;
public class countWordOccurs
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a character : ");
String str =sc.nextLine( );
String word= "the";
int count=0;
for(int i=0; i<str.length();i++)
{
if(str.contains(word)){
count+=1;
i+=word.length()-1;
}
}
System.out.println("words: " + count);
}
}
12 . Write a program to get input a string from user and Count no of words in a string and print each word in separate line.
import java.util.*;
public class longestWord
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a character : ");
String str =sc.nextLine();
str+="";
String word[]= str.split(" ");
String longest="";
int l, max=0, maxlnd=0;
for(int i=0; i<word.length;i++){
l=word[i].length();
if(l>word[0].length())
{
max=l;
maxlnd=i;
}
}
System.out.println("words: " + word[maxlnd]);
}
}
13 . Write a program to capitalize first letter of each word in the sentence
import java.util.*;
public class firstLetterEachWord
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a character : ");
String str =sc.nextLine();
StringBuilder result = new StringBuilder(str.length());
String words[] = str.split(" ");
for (int i = 0; i < words.length; i++)
{
result.append(Character.toUpperCase(words[i].charAt(0))).append(words[i].substring(1)).append(" ");
}
System.out.println(result);
}
}
14 . Write a program to swap the first and last letter of each word.
import java.util.*;
public class SwapFirstLastCharacters
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter any String");
String str = sc.nextLine();
char[] c = str.toCharArray();
for (int i = 0; i < c.length; i++) {
int k = i;
while (i < c.length && c[i] != ' ')
i++;
char temp = c[k];
c[k] = c[i - 1];
c[i - 1] = temp;
}
System.out.println((c));
}
}
15 . Write a program to get input a string from user and Print the frequency of each character
import java.util.Scanner;
public class frequencyEachCharacter
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int allpha=256;
int count[] = new int[allpha];
System.out.println("Enter a string : ");
String str =sc.nextLine( );
for(int i=0; i<str.length();i++)
{
count[(int) str.charAt(i)]++;
}
for (int i = 0; i < 256; i++) {
if (count[i] != 0)
System.out.println((char) i + " occurred for: " + count[i]);
}
}
}
16 . Declare a class BinSearch and a method binSearch( ). Write a program to assign 5 names in a array of string in Ascending order (ie. already sorted). Input a name N. Search N from the sorted array using Binary search method. Print the index of N (name) from the sorted list if N is found otherwise print “name not listed in the group”. Make a function Result() to create the object of class BinSearch and invoke the function binSearch() to print the desired output.
import java.io.*; import java.util.*; public class BinSearch { public void binSearch( ) { Scanner std = new Scanner(System.in); String N; String name[ ] = {"Amazing","Dynamic", "Jacob", "Laptop", "Linux"}; System.out.print("Input the name to search:" ); N = std. nextLine( ); int pos = -1, mid = 0; int start = 0, last = 9; while(start<=last) { mid = (start + last)/2; if( N. compareTo( name[ mid ]) == 0 ) { pos = mid; break; } else if( N. compareTo( name[ mid]) >0) start = mid + 1; else if( N. compareTo( name[ mid ]) <0) last = mid - 1; } if( pos == -1) System.out.println("Name not listed in the group"); else System.out.println("The Name "+ N +" is found at" + pos +" index "); } public static void Result( ) throws IOException { BinSearch obj = new BinSearch( ); obj.binSearch( ); } }
17 . Write a program to count Capital Letters, Small Letters, Digit and Space in a String.
import java.util.*;
public class CountCharacters
{
String str;
int countUpperCase= 0, countLowerCase= 0, countDigit= 0, countSpace=0;
public void takeInput()
{
Scanner in = new Scanner(System.in);
System.out.printf("Enter the String");
str = in.nextLine();
}
public void countChars()
{
char ch;
for (int i=0;i<str.length();i++)
{
ch = str.charAt(i);
if(Character.isUpperCase(ch))
countUpperCase++;
if(Character.isLowerCase(ch))
countLowerCase++;
if(Character.isDigit(ch))
countDigit++;
if(Character.isWhitespace(ch))
countSpace++;
}
}
void printChars()
{
System.out.println("Capital Letters: " + countUpperCase);
System.out.println("Small Letters: " + countLowerCase);
System.out.println("Digit: " + countDigit);
System.out.println("Space: " + countSpace);
}
public static void main(String [] args)
{
CountCharacters CC = new CountCharacters();
CC.takeInput();
CC.countChars();
CC.printChars();
}
}
18 . Write a program to take input a file name with full path as given below.
Using library functions, extract and output the file path, file name and file extension separately as shown.
Input C:\Users\SimplyCoding\Pictures\flower.jpg
Output Path: C:\Usersladmin\Pictures
File name : flower
Extension : jpg
import java.io.*;
public class FilePath
{
public static void main(String args[ ]) throws IOException
{
BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
String str, path, fileName, extension;
int x, y;
System.out.print("Enter the full path of the file, as given in example = ");
str = br. readLine();
x = str. lastIndexOf( '\\');
y = str. lastIndexOf( '.' );
path = str. substring( 0, (x+1) );
fileName = str.substring( (x+1), y );
extension = str.substring( (y+1) );
System.out.println("Output :");
System.out.println("Path : "+path);
System.out.println("File Name : "+fileName);
System.out.println("Extension : "+extension);
}
}
19 . Write a program to enter a sentence from the keyboard and count the number of times a particular word, occurs in it. Display the frequency of the search word.
Example :
INPUT :->
Enter a sentence : the quick brown fox jumps over the lazy dog.
Enter a word to be searched : the
OUTPUT :->
Searched word occurs : 2 times.
import java.io.*;
import java.util.*;
public class FindWord
{
public static void main(String args[ ]) throws IOException
{
int count = 0;
BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));
String InS, S_word, temp="";
Scanner scr = new Scanner( System.in );
System.out.print("Enter a Sentence = ");
InS = inp . readLine( );
System.out.print("Enter a Word to be Searched = ");
S_word = scr. next( );
InS = InS + " ";
int size = InS. length( );
for (int y = 0; y < size; y++)
{
char ch = InS. charAt( y );
if(ch!=' ')
temp = temp + ch;
else
{
if( S_word.compareTo( temp )==0)
count++;
temp = "";
}
}
System.out.print("Output: Search word occurs : "+ count+" times");
}
}
20. Design a function void findWords(String sent). The argument ‘sent’ contains a sentence/string- Write a program to print the sentence along with longest and smallest word.
Example:
Input: Honesty is the best policy
Output: Longest word : Honesty
Smallest word: is
public class FindWords
{
public void findWords( String sent )
{
String temp = "";
String Lword = "",Sword = "";
int i, s, g=0;
sent = sent +" ";
int len = sent.length( );
s = len;
for( i =0; i < len; i++)
{
char st = sent.charAt( i );
if( st !=' ')
temp = temp + st;
else
{
int Z = temp . length( );
if( Z > g)
{
Lword = temp;
g = Z;
}
else if( Z <s)
{
Sword = temp;
s = Z;
}
temp = "";
}
}
System.out.println("Longest word = "+ Lword);
System.out .println("Smallest word = "+ Sword);
}
}
21 . Write a program to input a string and print the following form:
Input: Simply
Output: S
S i
S i m
S i m p
S i m p l
S i m p l y
import java.util.Scanner;
public class Pattern2
{
public void Pattern()
{
Scanner inp= new Scanner( System.in );
String str;
int i, j, len;
System.out.print("Enter a string of your choice:");
str = inp . nextLine( );
len = str. length();
System.out.println("Output:");
for( i= 0; i < len; i++ )
{
for( j = 0; j <= i; j++ )
{
char ch = str.charAt( j );
System.out.print(ch+" ");
}
System.out.println( );
}
}
}
22 . Write a program to get input a string from user and convert it into Pig Latin.
Pig Latin:
- For Words beginning with consonants, move all the letters before the first vowel and keep them at the back. Add ‘AY’ at the back.
- For Words beginning with vowels, add ‘WAY’ at the back.
Example:
“pig” = “igpay”
“eat” = “eatway”
import java.util.*;
public class Piglatin
{
String str, newStr = "";
public void takeInput()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the string");
str = in.nextLine();
}
public void convert()
{
int start = 0, end = 0;
String word = "";
String str4 = str + " ";
do
{
end = str4.indexOf(' ');
word = str4.substring(start,end);
word = word.toUpperCase();
for(int i = 0; i < word.length();i++)
{
char ch = word.charAt(i);
if(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
{
newStr= newStr+word.substring(i)+word.substring(0,i)+"AY";
break;
}
}
str4 = str4.substring(end+1);
start = end = 0;
}while (str4.indexOf(' ') > 0);
newStr.trim();
}
public void printOutput()
{
System.out.println(newStr.trim());
}
public static void main (String [] args)
{
Piglatin CU = new Piglatin();
CU.takeInput();
CU.convert();
CU.printOutput();
}
}
23 . Write a program to input a name and print the initials of that name except the last word (surname), each initial must be followed by symbol dot ().
Example :
Input : Mohandas Karamchand Gandhi
Output : M. K. Gandhi
import java.util.Scanner;
public class Printlnitials
{
public static void main( String args[ ])
{
int x, L, pos=0; char ch;
Scanner inp = new Scanner(System.in );
String name, last_word = "";
System.out.print("Enter a full name = ");
name = inp. nextLine( );
L = name. length( );
for( x = L-1; x >= 0; x--)
{
ch = name.charAt( x );
if( ch==' ')
{
pos = x;
break;
}
}
last_word = name. substring( pos+1, L );
System.out.print("The initials are: ");
System.out.print(name.charAt( 0 ) +". ");
for( x = 1; x < pos ; x++)
{
ch = name.charAt( x );
if(ch==' ')
{
System.out.print(name.charAt( x+1 ) +". ");
}
}
System.out.println( last_word );
}
}
24 . Special words are those which starts and ends with the same letter.
Examples: EXISTENCE, COMIC, WINDOW etc.
Palindrome words are those which read the same from left to right and vice-versa.
Examples: MADAM, LEVEL, ROTATOR, CIVIC etc.
All palindrome words are special words, but all special words are not palindromes.
Write a program to accept a word, check and print whether the word is a palindrome or only special word.
import java.io.*;
import java.util .*;
public class SpecialWords
{
void checkWord()
{
Scanner scr = new Scanner( System.in );
String word, NewWord = "";
System.out.print("Input a word = ");
word = scr. next( );
int size = word . length( );
for( int j = size-1; j>= 0 ; j--)
{
char c = word. charAt( j );
NewWord = NewWord + c;
}
if( word. equalsIgnoreCase( NewWord) )
{
System.out.println(word + " is a palindrome and also special word ");
}
else if( word.charAt(0) == word.charAt(size-1))
{
System.out.println( word + " is only a special word ");
}
}
}
25 . Write a program to assign any 12 characters in an array. Merge all the characters in the form of a string and print the string with suitable message.
public class String1
{
public void show()
{
char data[ ] = {'S','i','m','p','l','y','','C','o','d','i','n', 'g'};
String st = new String( data );
System.out.println("OUTPUT:");
System.out.println("The string stored in st = " + st );
}
}
26. Write a program to capitalize each word in string
Ans.
String s = "This is a String";
s+=" ";
String word= "", s1= "";
int end=0, position=0, l=0;
while(s.indexOf(' ' , position)>0)
{
end = s.indexOf(' ' , position);
word = s.substring(position, end);
s1 = s1+ character.toUpperCase(word.charAt(0));
s1 = s1+ word.substing(1)+"";
position= end+1;
};
System.out.println(s1.trim());