STRING
PROGRAMS
PROGRAM 26
Design a class in java to accept a string and display the new string after
encoding.
Sample input:
Enter a sentence: Good morning.
Enter the shift value: 3
Sample output:
Encoded text:
Jrrg pruqlqj
ALGORITHM
Algorithm for acceptInput()
Step 1:- Start
Step 2:- Display a message prompting the user to enter a sentence.
Step 3:- Read and store the input sentence in a variable (inputString).
Step 4:- Display a message asking the user to enter the shift value.
Step 5:- Read and store the shift value in a variable (shiftValue).
Step 6:- End.
Algorithm for encodeString()
Step 1:- Start
Step 2:- Initialize an empty string encodedString.
Step 3:- Create a character array inputChars with the same length as
inputString.
Step 4:- Copy each character from inputString to inputChars using a loop.
Step 5:- Iterate through each character in inputChars.
Step 5.1:- If the character is a letter.
Step 5.2:- Determine whether it is uppercase or lowercase.
Step 5.3:- Apply the Caesar cipher formula to shift the character.
Step 5.4:- Append the encoded character to encodedString.
Step 5.5:- Else, append the character as it is to encodedString.
Step 6:- Return encodedString.
Step 7:- End.
Algorithm for displayEncodedString()
Step 1:- Start
Step 2:- Call the encodeString() function and store the returned value in
encodedText.
Step 3:- Print "Encoded text:".
Step 4:- Print the encodedText.
Step 5:- End.
Algorithm for main()
Step 1:- Start
Step 2:- Call acceptInput() to take user input.
Step 3:- Call displayEncodedString() to display the encoded text.
Step 4:- End.
CODE:
METHOD/FuNCTION DESCRIPTION:
Function Name Access Specifier Return Type Description
acceptInput() default void Accepts the user input for
the sentence and shift
value.
encodeString() default String Encodes the input string
using the Caesar Cipher
method and returns the
encoded string.
displayEncodedString() default void Calls the encodeString()
and displays the encoded
String.
main(String[] args) public void Creates an object of the
class and calls
acceptInput() and
displayEncodedString()
functions.
VARIAbLE DESCRIPTION:
Variable Name Datatype Description
inputString String Stores the user input
sentence.
shiftValue int Stores the user input shift
value.
encodedString String Stores the encoded version
of the input string.
inputChars[] char Stores the characters of the
input string.
ch char Stores the current character
being processed.
base char Stores base character (‘a’ for
lowercase, ‘A’ for uppercase)
encodedText String Stores the final encoded
String for display.
i int Loop variable which iterates
over the character array.
OuTPuT :
PROGRAM 27
Caesar Cipher is an encryption technique which is implemented as ROT 13
('rotate by 13 places"). It is a simple letter substitution cipher that replaces a
letter with the letter 13 places after it in the alphabets, with the other
characters remaining unchanged.
Design a class to accept a plain text of length L, where L must be greater than 3
and less than 100.
Encrypt the text if valid as per the Caesar Cipher.
Test your program with the sample data and some random data:
Example 1
INPUT: Hello! How are you?
OUTPUT: The cipher text is:
Uryyb! Ubjnerlbh?
Example 2
INPUT: You
OUTPUT: INVALID LENGTH
ALGORITHM
Algorithm for main()
Step 1:- Start
Step 2:- Print a message prompting the user to enter text.
Step 3:- Read the user input and store it in text.
Step 4:- If the length of text is less than or equal to 3 OR greater than or equal
to 100.
Step 4.1:- Print an error message indicating the valid length range.
Step 5:- Else.
Step 5.1:- Call encrypt(text) to get the encrypted version.
Step 5.2:- Print "Encrypted text: " followed by the encrypted text.
Step 6:- End.
Algorithm for encrypt(text)
Step 1:- Start
Step 2:- Create a character array encryptedChars of the same length as text.
Step 3:- Loop from i = 0 to [Link]() - 1.
Step 3.1:- Extract the character at position i and store it in ch.
Step 3.2:- If ch is an uppercase letter.
Step 3.3:- Apply the ROT13 encryption formula for uppercase letters.
Step 3.4:- Store the encrypted character in encryptedChars[i].
Step 3.5:- Else if ch is a lowercase letter.
Step 3.6:- Apply the ROT13 encryption formula for lowercase letters.
Step 3.7:- Store the encrypted character in encryptedChars[i].
Step 3.8:- Else, store ch unchanged in encryptedChars[i].
Step 4:- Convert encryptedChars to a string and return it.
Step 5:- End.
CODE:
METHOD/FuNCTION DESCRIPTION:
Function Name Access Specifier Return Type Description
main(String[] args) public void Reads user input, validates
text length and encrypts
text if valid.
encrypt(String text) public String Encrypts the input text
using ROT13 method and
returns the encrypted
text.
VARIAbLE DESCRIPTION:
Variable Name Datatype Description
text String Stores the user input text.
encryptedChars[] char Stores the encrypted
characters before converting
to String.
ch char Stores the current character
being processed.
i int Loop variable which iterates
over each character in the
input text.
OuTPuT :
PROGRAM 28
Design a class in java to accept two words and check whether they are anagram
or not.
The words that are made with the combinations of the letters present in the
original word are called anagram.
Example:
FLOW and WOLF are anagram words.
ALGORITHM
Algorithm for main() function
Step 1:- Start
Step 2:- Prompt the user to enter the first word.
Step 3:- Read the first word and convert it to lowercase.
Step 4:- Prompt the user to enter the second word.
Step 5:- Read the second word and convert it to lowercase.
Step 6:- Call the function areAnagrams(first word, second word)
Step 6.1:- If it returns true, print “Words are anagrams.”
Step 6.2:- Otherwise, print “Words are not anagrams.”
Step 7:- End.
Algorithm for areAnagrams(word1, word2) function
Step 1:- Start
Step 2:- If the lengths of word1 and word2 are not equal, return false.
Step 3:- Create two character arrays of the same size as the words.
Step 4:- Convert word1 into charArray1.
Step 4.1:- Loop from i = 0 to length - 1
Step 4.2:- Assign each character of word1 to charArray1
Step 5:- Convert word2 into charArray2 manually:
Step 5.1:- Loop from i = 0 to length - 1
Step 5.2:- Assign each character of word2 to charArray2
Step 6:- Call selectionSort(charArray1) to sort charArray1.
Step 7:- Call selectionSort(charArray2) to sort charArray2.
Step 8:- Compare both sorted arrays element by element.
Step 8.1:- If any character does not match, return false.
Step 9:- If all characters match, return true.
Step 10:- End
Algorithm for selectionSort(array) function
Step 1:- Start
Step 2:- Get the length (n) of the array.
Step 2.1:- Loop from i = 0 to n - 2
Step 2.2:- Assume minIndex = i (smallest element's index).
Step 2.3:- Loop from j = i + 1 to n - 1.
Step 2.4:- If array[j] < array[minIndex], update minIndex = j
Step 2.5:- Swap array[i] and array[minIndex].
Step 3:- End.
CODE:
METHOD/FuNCTION DESCRIPTION:
Function Name Access Specifier Return Type Description
main(String[] args) public void Reads user input and
checks if words are
anagrams by calling
areAnagrams() function
and prints the result.
areAnagrams(word1, private boolean Checks if two words are
word2) anagrams by sorting and
comparing their
characters.
selectionSort(array) private void Sorts a character array
using Selection Sort.
VARIAbLE DESCRIPTION:
Variable Name Datatype Description
word1 String Stores the first word
entered by the user.
Word2 String Stores the second word
entered by the user.
charArray1[] char Stores the characters of the
first word.
charArray2[] char Stores the characters of the
second word.
i int Used in loops for sorting.
j int Used in loops for sorting.
minIndex int Stores the index of the
minimum element during
selection sort.
temp char Temporary variable used for
swapping elements.
OuTPuT :
PROGRAM 29
Design a class to accept a sentence which may be terminated by either'.',
'?'or'!' only. The words may be separated by more than one blank space and
are in UPPER CASE.
(a) Find the number of words beginning and ending with a vowel.
(b) Place the words which begin and end with a vowel at the beginning,
followed by the remaining words as they occur in the sentence.
Test your program with the sample data and some random data:
Example 1
INPUT: ANAMIKA AND SUSAN ARE NEVER GOING TO QUARREL ANYMORE.
OUTPUT: NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL= 3
ΑΝΑΜΙΚΑ ARE ANYMORE AND SUSAN NEVER GOING TO QUARREL
ALGORITHM
Algorithm for main()
Step 1:- Start
Step 2:- Display a message asking the user to enter a sentence ending with '.',
'?' or '!'.
Step 3:- Read the input sentence and remove any leading or trailing spaces.
Step 4:- If the last character of the sentence is '.', '?' or '!', remove it.
Step 5:- Call the function countVowelWords(sentence) to count words that
start and end with a vowel.
Step 6:- Display the count of words that start and end with a vowel.
Step 7:- Call the function reorderSentence(sentence) to reorder the sentence.
Step 8:- Display the reordered sentence.
Step 9:- End.
Algorithm for countVowelWords(sentence)
Step 1:- Start
Step 2:- Initialize count to 0.
Step 3:- Split the sentence into words using spaces.
Step 4:- Loop through each word from index 0 to length - 1.
Step 4.1:- If the word starts and ends with a vowel, increment count.
Step 4.2:- Return the final count.
Step 5:- End.
Algorithm for startsWithVowel(word)
Step 1:- Start
Step 2:- Extract the first character of the word.
Step 3:- Convert the character to uppercase.
Step 4:- If it is one of {A, E, I, O, U}, return true.
Step 5:- Otherwise, return false.
Step 6:- End.
Algorithm for endsWithVowel(word)
Step 1:- Start
Step 2:- Extract the last character of word.
Step 3:- Convert the character to uppercase.
Step 4:- If it is one of {A, E, I, O, U}, return true.
Step 5:- Otherwise, return false.
Step 6:- End.
Algorithm for reorderSentence(sentence)
Step 1:- Start
Step 2:- Split the sentence into words.
Step 3:- Initialize two empty strings: vowelWords and otherWords.
Step 4:- Loop through each word from index 0 to length - 1.
Step 4.1:- If the word starts and ends with a vowel, add it to vowelWords.
Step 4.2:- Otherwise, add it to otherWords.
Step 5:- Concatenate vowelWords and otherWords with a space in between.
Step 6:- Return the concatenated string.
Step 7:- End.
CODE:
METHOD/FuNCTION DESCRIPTION:
Function Name Access Specifier Return Type Description
main(String[] args) public void Reads user input,
processes it and displays
the result.
countVowelWords(String private int Counts words that begin
sentence) and end with vowel.
startsWithVowel(String private boolean Checks if a word starts
word) with a vowel.
endsWithVowel(String private boolean Checks if a word ends with
word) a vowel.
reorderSentence(String private String Moves words that start
sentence) and end with vowels to
the front of the sentence.
VARIAbLE DESCRIPTION:
Variable Name Datatype Description
sentence String Stores the input sentence
entered by the user.
vowelWordsCount int Stores the count of words
that start and end with a
vowel.
reorderSentence String Stores the sentence after
reordering words.
count int Keeps track of the number
of words that start and end
with a vowel.
words[] String Stores an array of words
from the sentence.
firstChar char Stores the first character of
a word.
lastChar char Stores the last character of a
word.
vowelWords String Stores words that start and
end with a vowel.
otherWords String Stores other words.
OuTPuT :
PROGRAM 30
Design a class in java to accept number of sentence and the sentence & display
the number of words and the words in ascending order of their frequency.
Sample input:
Enter number of sentence: 1
Enter sentences: TO BE OR NOT TO BE
Sample output:
Total number of words: 6
Word Frequency
OR 1
NOT 1
TO 2
BE 2
ALGORITHM
Step 1:- Start
Step 2:- Print "Enter number of sentences."
Step 3:- Accept integer n from the user.
Step 4:- If n is less than 1 or greater than 3, print "Invalid Entry" and STOP.
Step 5:- Print "Enter sentences."
Step 6:- Accept input sentence(s) as a string.
Step 7:- Convert the string to uppercase.
Step 8:- Tokenize the string using space and punctuation as delimiters.
Step 9:- Count the total number of words.
Step 10:- Initialize empty arrays.
Step 10.1:- wordArr[] for unique words.
Step 10.2:- wordFreq[] for word frequencies.
Step 11:- Initialize an index variable idx = 0 to track unique words.
Step 12:- For each word in the tokenized string.
Step 12.1:- Check if the word already exists in wordArr[].
Step 12.2:- If found, increase its frequency.
Step 12.3:- If not found, add it to wordArr[] and set its frequency to 1.
Step 12.4:- Increment idx for the next unique word.
Step 13:- Sort the words in descending order of frequency using Bubble Sort.
Step 14:- Print the words along with their frequencies.
Step 15:- End.
CODE:
METHOD/FuNCTION DESCRIPTION:
Function Name Access Specifier Return Type Description
main(String[] args) public void Reads user input,
processes word frequency
and displays results.
VARIAbLE DESCRIPTION:
Variable Name Datatype Description
n int Number of sentences
entered by the user.
ipStr String Stores the user input
sentence in uppercase.
st StringTokenizer Splits the input string into
individual words.
wordCount int Stores the total number of
words in the input.
wordArr[] String Stores unique words from
the input.
wordFreq[] int Stores frequency of words
corresponding to wordArr[].
idx int Tracks the number of
unique words stored in
wordArr[].
word String Temporarily stores the
currently processed word.
i int Loop variable used for
iterating through words and
sorting.
j int Iterator for checking existing
words in wordArr[].
t int Temporary variable for
swapping frequencies in
sorting.
temp String Temporary variable for
swapping words in sorting.
OuTPuT :