0% found this document useful (0 votes)
3 views30 pages

Java String Problems Study Guide Updated 1

Uploaded by

manjunathen03
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)
3 views30 pages

Java String Problems Study Guide Updated 1

Uploaded by

manjunathen03
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

JavaA Revision

String Problems
& Practice Guide

26 Classic String-Handling Problems in Java


Each problem includes the question, an example, the approach, time complexity, and full working
code.

1
Contents
1. Check if a Given String is a Palindrome or Not
2. Count Vowels, Consonants and Spaces
3. Find ASCII Value of a Character
4. Remove All Vowels
5. Remove Spaces
6. Remove Characters Except Alphabets
7. Reverse a String
8. Remove Brackets from an Algebraic Expression
9. Sum of Numbers in a String
10. Capitalize First and Last Character of Every Word
11. Calculate Frequency of Characters
12. Find Non-Repeating Characters
13. Check if Two Strings are Anagrams
14. Maximum Occurring Character
15. Remove All Duplicate Characters
16. Print All Duplicate Characters
17. Remove Characters from First String Present in Second String
18. Change Every Letter to the Next Lexicographic Alphabet
19. Find the Largest Word in a String
20. Sort Characters in a String
21. Count Number of Words in a String
22. Find the Word with the Highest Number of Repeated Letters
23. Change Case of Each Character
24. Concatenate One String to Another
25. Find a Substring and Display its Starting Position
26. Reverse Words in a String

2
1. Check if a Given String is a Palindrome or Not
Question
A palindrome is a string that reads the same forwards and backwards.

Example
Input:
madam
Output:
Palindrome

Approach
Compare characters from the beginning and end. If any pair differs, it's not a palindrome.

Time Complexity
O(n)

Java Code
public class Palindrome {
public static void main(String[] args) {
String str = "madam";
int left = 0;
int right = [Link]() - 1;
boolean palindrome = true;

while (left < right) {


if ([Link](left) != [Link](right)) {
palindrome = false;
break;
}
left++;
right--;
}

if (palindrome)
[Link]("Palindrome");
else
[Link]("Not Palindrome");
}
}

3
2. Count Vowels, Consonants and Spaces
Question
Count the number of vowels, consonants, and spaces present in a given string.

Example
Input:
Hello World
Output:
Vowels = 3
Consonants = 7
Spaces = 1

Approach
Convert the string to lowercase, then iterate through each character, classifying it as a vowel,
consonant, or space.

Time Complexity
O(n)

Java Code
public class CountCharacters {
public static void main(String[] args) {
String str = "Hello World";
int vowels = 0;
int consonants = 0;
int spaces = 0;

str = [Link]();

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


char ch = [Link](i);
if (ch == ' ')
spaces++;
else if (ch == 'a' || ch == 'e' || ch == 'i'
|| ch == 'o' || ch == 'u')
vowels++;
else if (ch >= 'a' && ch <= 'z')
consonants++;
}

[Link]("Vowels = " + vowels);


[Link]("Consonants = " + consonants);
[Link]("Spaces = " + spaces);
}
}

4
3. Find ASCII Value of a Character
Question
Given a character, find and print its ASCII (numeric) value.

Example
Input:
A
Output:
65

Approach
Cast the char to an int; Java automatically converts it to its ASCII value.

Time Complexity
O(1)

Java Code
public class ASCIIValue {
public static void main(String[] args) {
char ch = 'A';
int ascii = (int) ch;
[Link](ascii);
}
}

5
4. Remove All Vowels
Question
Remove all vowels (a, e, i, o, u) from a given string.

Example
Input:
education
Output:
dctn

Approach
Iterate through the string, and append every character to the result only if it is not a vowel.

Time Complexity
O(n)

Java Code
public class RemoveVowels {
public static void main(String[] args) {
String str = "education";
StringBuilder ans = new StringBuilder();

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


char ch = [Link]([Link](i));
if (!(ch == 'a' || ch == 'e' || ch == 'i'
|| ch == 'o' || ch == 'u')) {
[Link]([Link](i));
}
}

[Link](ans);
}
}

6
5. Remove Spaces
Question
Remove all the spaces from a given string.

Example
Input:
Hello World Java
Output:
HelloWorldJava

Approach
Iterate through the string and append every character except spaces to the result.

Time Complexity
O(n)

Java Code
public class RemoveSpaces {
public static void main(String[] args) {
String str = "Hello World Java";
StringBuilder ans = new StringBuilder();

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


if ([Link](i) != ' ')
[Link]([Link](i));
}

[Link](ans);
}
}

7
6. Remove Characters Except Alphabets
Question
Given a string containing letters, digits, and symbols, keep only the alphabetic characters.

Example
Input:
abc123@#$DEF
Output:
abcDEF

Approach
Check each character's range (A-Z or a-z) and append only alphabetic characters to the result.

Time Complexity
O(n)

Java Code
public class OnlyAlphabets {
public static void main(String[] args) {
String str = "abc123@#$DEF";
StringBuilder ans = new StringBuilder();

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


char ch = [Link](i);
if ((ch >= 'A' && ch <= 'Z') ||
(ch >= 'a' && ch <= 'z'))
[Link](ch);
}

[Link](ans);
}
}

8
7. Reverse a String
Question
Reverse the characters of a given string.

Example
Input:
hello
Output:
olleh

Approach
Traverse the string from the last character to the first, appending each character to a new StringBuilder.

Time Complexity
O(n)

Java Code
public class ReverseString {
public static void main(String[] args) {
String str = "hello";
StringBuilder rev = new StringBuilder();

for (int i = [Link]() - 1; i >= 0; i--) {


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

[Link](rev);
}
}

9
8. Remove Brackets from an Algebraic Expression
Question
Given an algebraic expression containing brackets, remove all the brackets.

Example
Input:
(a+b)-(c*d)
Output:
a+b-c*d

Approach
Iterate through the string and skip appending any '(' or ')' characters to the result.

Time Complexity
O(n)

Java Code
public class RemoveBrackets {
public static void main(String[] args) {
String str = "(a+b)-(c*d)";
StringBuilder ans = new StringBuilder();

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


char ch = [Link](i);
if (ch != '(' && ch != ')')
[Link](ch);
}

[Link](ans);
}
}

10
9. Sum of Numbers in a String
Question
Given a string containing letters and digits, find the sum of all the numbers embedded in it.

Example
Input:
abc12xy3z5
Output:
20

Approach
Build up a number digit by digit while scanning digit characters; whenever a non-digit is hit, add the
accumulated number to the sum and reset it. Add the final number after the loop ends.

Time Complexity
O(n)

Java Code
public class SumNumbers {
public static void main(String[] args) {
String str = "abc12xy3z5";
int sum = 0;
int num = 0;

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


char ch = [Link](i);
if ([Link](ch)) {
num = num * 10 + (ch - '0');
} else {
sum += num;
num = 0;
}
}
sum += num;

[Link](sum);
}
}

11
10. Capitalize First and Last Character of Every Word
Question
Given a sentence, capitalize the first and last character of every word.

Example
Input:
hello world java
Output:
HellO WorlD JavA

Approach
Split the sentence into words. For each word, capitalize the first and last character; for a single-letter
word, just capitalize that one letter.

Time Complexity
O(n)

Java Code
public class CapitalizeFirstLast {
public static void main(String[] args) {
String str = "hello world java";
String[] words = [Link](" ");
StringBuilder ans = new StringBuilder();

for (String word : words) {


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

[Link]([Link]().trim());
}
}

12
11. Calculate Frequency of Characters
Question
Given a string, calculate the frequency (count) of each character in it.

Example
Input:
banana
Output:
b -> 1
a -> 3
n -> 2

Approach
Use a HashMap to store each character as a key and its count as the value, incrementing the count as
each character is scanned.

Time Complexity
O(n)

Java Code
import [Link].*;

public class FrequencyCharacters {


public static void main(String[] args) {
String str = "banana";
HashMap<Character, Integer> map = new HashMap<>();

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


char ch = [Link](i);
[Link](ch, [Link](ch, 0) + 1);
}

for (char key : [Link]()) {


[Link](key + " -> " + [Link](key));
}
}
}

13
12. Find Non-Repeating Characters
Question
Given a string, find all the characters that appear exactly once (in their original order).

Example
Input:
programming
Output:
p o a i n

Approach
First pass: build a frequency map of all characters. Second pass: print characters whose frequency is
exactly 1, preserving original order.

Time Complexity
O(n)

Java Code
import [Link].*;

public class NonRepeating {


public static void main(String[] args) {
String str = "programming";
HashMap<Character, Integer> map = new HashMap<>();

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


char ch = [Link](i);
[Link](ch, [Link](ch, 0) + 1);
}

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


char ch = [Link](i);
if ([Link](ch) == 1)
[Link](ch + " ");
}
}
}

14
13. Check if Two Strings are Anagrams
Question
Given two strings, determine whether they are anagrams of each other (contain the same characters
with the same frequency).

Example
Input:
listen
silent
Output:
Anagram

Approach
If the lengths differ, they can't be anagrams. Otherwise, use a frequency array of size 26: increment for
characters in the first string, decrement for characters in the second. If all counts end at zero, they're
anagrams.

Time Complexity
O(n)

Java Code
public class Anagram {
public static void main(String[] args) {
String s1 = "listen";
String s2 = "silent";

if ([Link]() != [Link]()) {
[Link]("Not Anagram");
return;
}

int[] freq = new int[26];


for (int i = 0; i < [Link](); i++) {
freq[[Link](i) - 'a']++;
freq[[Link](i) - 'a']--;
}

boolean anagram = true;


for (int i = 0; i < 26; i++) {
if (freq[i] != 0) {
anagram = false;
break;
}
}

if (anagram)
[Link]("Anagram");
else

15
[Link]("Not Anagram");
}
}

16
14. Maximum Occurring Character
Question
Given a string, find the character that occurs the most number of times, along with its frequency.

Example
Input:
success
Output:
s
Frequency = 3

Approach
Use an array of size 256 to count the frequency of every character (indexed by its ASCII value). Then
scan the string again to find the character with the highest recorded frequency.

Time Complexity
O(n)

Java Code
public class MaximumOccurringCharacter {
public static void main(String[] args) {
String str = "success";
int[] freq = new int[256];

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


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

int max = 0;
char ans = ' ';
for (int i = 0; i < [Link](); i++) {
if (freq[[Link](i)] > max) {
max = freq[[Link](i)];
ans = [Link](i);
}
}

[Link](ans);
[Link](max);
}
}

17
15. Remove All Duplicate Characters
Question
Given a string, remove all duplicate characters so that each character appears only once, keeping the
first occurrence.

Example
Input:
programming
Output:
progamin

Approach
Use a HashSet to track characters already seen. Scan the string and append a character to the result
only if it hasn't been seen before, then add it to the set.

Time Complexity
O(n)

Java Code
import [Link].*;

public class RemoveDuplicates {


public static void main(String[] args) {
String str = "programming";
HashSet<Character> set = new HashSet<>();
StringBuilder ans = new StringBuilder();

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


char ch = [Link](i);
if (![Link](ch)) {
[Link](ch);
[Link](ch);
}
}

[Link](ans);
}
}

18
16. Print All Duplicate Characters
Question
Given a string, print all the characters that occur more than once in it.

Example
Input:
programming
Output:
r
g
m

Approach
Use a HashMap to store the frequency of each character. Then iterate over the map's keys and print
any character whose frequency is greater than 1.

Time Complexity
O(n)

Java Code
import [Link].*;

public class DuplicateCharacters {


public static void main(String[] args) {
String str = "programming";
HashMap<Character, Integer> map = new HashMap<>();

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


char ch = [Link](i);
[Link](ch, [Link](ch, 0) + 1);
}

for (char ch : [Link]()) {


if ([Link](ch) > 1)
[Link](ch);
}
}
}

19
17. Remove Characters from First String Present in Second
String
Question
Remove all characters from the first string that are present in the second string.

Example
Input:
String1 = "computer"
String2 = "cat"
Output:
ompuer

Approach
Store all characters of the second string in a HashSet. Traverse the first string. Append only characters
that are not in the set.

Time Complexity
O(n + m)

Java Code
import [Link].*;

public class RemoveCharacters {


public static void main(String[] args) {
String str1 = "computer";
String str2 = "cat";
HashSet<Character> set = new HashSet<>();

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


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

StringBuilder ans = new StringBuilder();


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

[Link](ans);
}
}

20
18. Change Every Letter to the Next Lexicographic Alphabet
Question
Given a string, change every letter to the next letter in lexicographic (alphabetical) order, wrapping 'z' to
'a' and 'Z' to 'A'.

Example
Input:
abcdxyz
Output:
bcdeyza

Approach
Iterate through the string. For each character, if it is 'z' wrap to 'a', if it is 'Z' wrap to 'A', otherwise shift it
to the next character.

Time Complexity
O(n)

Java Code
public class NextAlphabet {
public static void main(String[] args) {
String str = "abcdxyz";
StringBuilder ans = new StringBuilder();

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


char ch = [Link](i);
if (ch == 'z')
[Link]('a');
else if (ch == 'Z')
[Link]('A');
else
[Link]((char)(ch + 1));
}

[Link](ans);
}
}

21
19. Find the Largest Word in a String
Question
Given a sentence, find the largest (longest) word in it.

Example
Input:
Java is an object oriented programming language
Output:
programming

Approach
Split the sentence into words. Track the longest word seen so far by comparing lengths as you iterate.

Time Complexity
O(n)

Java Code
public class LargestWord {
public static void main(String[] args) {
String str = "Java is an object oriented programming language";
String[] words = [Link](" ");
String largest = "";

for (String word : words) {


if ([Link]() > [Link]())
largest = word;
}

[Link](largest);
}
}

22
20. Sort Characters in a String
Question
Given a string, sort its characters in alphabetical order.

Example
Input:
dcabfe
Output:
abcdef

Approach
Convert the string to a character array, sort the array using [Link](), then build a new string from
the sorted array.

Time Complexity
O(n log n)

Java Code
import [Link];

public class SortCharacters {


public static void main(String[] args) {
String str = "dcabfe";
char[] arr = [Link]();
[Link](arr);
[Link](new String(arr));
}
}

23
21. Count Number of Words in a String
Question
Given a string, count the number of words in it. (Method 1: using split())

Example
Input:
I love Java Programming
Output:
4

Approach
Trim the string and split it on one or more whitespace characters using split("\\s+"). The length of the
resulting array is the word count.

Time Complexity
O(n)

Java Code
public class CountWords {
public static void main(String[] args) {
String str = "I love Java Programming";
String[] words = [Link]().split("\\s+");
[Link]([Link]);
}
}

24
22. Find the Word with the Highest Number of Repeated
Letters
Question
Given a sentence, find the word that contains the letter with the highest number of repetitions within
that word.

Example
Input:
Apple committee programming
Output:
committee

Approach
Split the sentence into words. For each word, build a frequency array of its letters and find that word's
highest single-letter frequency. Track the word whose highest letter frequency is the greatest across all
words.

Time Complexity
O(n)

Java Code
class Main {
public static void main(String[] args) {
String str = "Apple committee programming";
String[] words = [Link](" ");
String ans = "-1";
int maxfreq = 1;

for (String word : words) {


int[] freq = new int[26];
// Count frequency
for (int i = 0; i < [Link](); i++) {
char ch = [Link]([Link](i));
if (ch >= 'a' && ch <= 'z') {
freq[ch - 'a']++;
}
}

// Find maximum frequency in this word


int currentmax = 1;
for (int count : freq) {
if (count > currentmax) {
currentmax = count;
}
}

// Update answer
if (currentmax > maxfreq) {

25
maxfreq = currentmax;
ans = word;
}
}

[Link](ans);
}
}

26
23. Change Case of Each Character
Question
Given a string, toggle the case of every letter: uppercase letters become lowercase and lowercase
letters become uppercase. Non-letter characters are left unchanged.

Example
Input:
HeLLo123
Output:
hEllO123

Approach
Iterate through the string. For each character, check if it is uppercase or lowercase using
[Link]()/isLowerCase() and append the opposite case; otherwise append the
character unchanged.

Time Complexity
O(n)

Java Code
public class ToggleCase {
public static void main(String[] args) {
String str = "HeLLo123";
StringBuilder ans = new StringBuilder();

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


char ch = [Link](i);
if ([Link](ch))
[Link]([Link](ch));
else if ([Link](ch))
[Link]([Link](ch));
else
[Link](ch);
}

[Link](ans);
}
}

27
24. Concatenate One String to Another
Question
Given two strings, join them together to form a single string.

Example
Input:
Hello
World
Output:
HelloWorld

Approach
Three common approaches: use the '+' operator, use the concat() method, or build the result with a
StringBuilder.

Time Complexity
O(n)

Java Code
// Method 1: '+' operator
public class Concatenate {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "World";
String result = s1 + s2;
[Link](result);
}
}

// Method 2: concat()
public class Concatenate {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "World";
[Link]([Link](s2));
}
}

// Method 3: StringBuilder
public class Concatenate {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
[Link]("Hello");
[Link]("World");
[Link](sb);
}
}

28
25. Find a Substring and Display its Starting Position
Question
Given a string and a substring, find the starting index at which the substring first occurs.

Example
Input:
Programming
gram
Output:
3

Approach
Read the main string and the substring from user input using Scanner, then use the built-in indexOf()
method to locate the starting index of the substring.

Time Complexity
O(n)

Java Code
import [Link].*;

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String str = [Link]();
String sub = [Link]();
int pos = [Link](sub);
if (pos != -1) {
[Link]("Substring found at position: " + pos);
} else {
[Link]("Substring not found");
}
}
}

29
26. Reverse Words in a String
Question
Given a sentence, reverse the order of the words in it (the letters within each word stay in the same
order).

Example
Input:
I love Java
Output:
Java love I

Approach
Split the sentence into words on spaces, then print the words array starting from the last index down to
the first.

Time Complexity
O(n)

Java Code
public class ReverseWords {
public static void main(String[] args) {
String str = "I love Java";
String[] words = [Link](" ");

for (int i = [Link] - 1; i >= 0; i--) {


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

30

You might also like