0% found this document useful (0 votes)
15 views97 pages

Lesson 4 - Strings (Classroom

This document provides an introduction to Strings in Java, explaining their characteristics, creation, and commonly used methods. It covers various string operations such as length, substring, case conversion, and comparison, along with examples and problem-solving techniques related to strings. Additionally, it includes practical coding problems like reversing a string, checking for palindromes, and finding the index of a substring.

Uploaded by

irineclara
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)
15 views97 pages

Lesson 4 - Strings (Classroom

This document provides an introduction to Strings in Java, explaining their characteristics, creation, and commonly used methods. It covers various string operations such as length, substring, case conversion, and comparison, along with examples and problem-solving techniques related to strings. Additionally, it includes practical coding problems like reversing a string, checking for palindromes, and finding the index of a substring.

Uploaded by

irineclara
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
You are on page 1/ 97

Java

Programming
Strings in Java
WHAT WILL
YOU LEARN ● Introduction to Strings.
IN THIS
Commonly used methods
SESSION ? ●

in Strings.
CREDITS: This presentation template was
● Solving
created byindustry level
Slidesgo, including icons by
Flaticon, and infographics & images by Freepik

problems on Strings.
01
Introduction to
Strings
Introduction to String
In Java, a string is a sequence of characters. For example, "hello" is
a string containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.

We use double quotes to represent a string in Java. For example,

// create a string
String type = "Java programming";

Here, we have created a string variable named type. The variable is


initialized with the string Java Programming.
Introduction to String

A string in java is an immutable object that


represents a sequence of characters. The
String class provides methods for dealing with
strings, such as examining their length,
concatenating them together, and searching
for particular characters within them.
Working with Strings
The most straightforward way to create a string in Java:
public class Main {
public static void main(String args[]) {
String str = "Hello World!";
System.out.println(str); // output will be: Hello
World!
}
}
Working with Strings
It is also possible to create a String using the new operator:

public class StringDemo {

public static void main(String args[]) {


String str = new String("Hello World!");
System.out.println(str); // output will be: Hello World!
}
}
02

Commonly used
methods in Strings.
1. length()

String str = "Hello, World!"; O/P:


int len = str.length(); 13
2. charAt(int index)

Description: Returns the character at the specified index.

String str = "HAPPY";


O/P:
char ch = str.charAt(3);
P
System.out.println(ch);
3. substring(int beginIndex)

Description: Returns a new string that is a substring of this string


from the specified index to the end.

String str = "ABCDEFG";


String substr1 = str.substring(1);
String substr2 = str.substring(3); O/P:
String substr3= str.substring(6); BCDEFG
System.out.println(substr1); DEFG
G
System.out.println(substr2);
System.out.println(substr3);
4. substring
(int beginIndex, int endIndex)
Description: Returns a new string that is a substring of this string
from the specified begin index to the end index (exclusive).

String str =
"ABCDEFGHIJKL"; O/P:
String substr = EFGH
str.substring(4,8);
System.out.println(substr);
5. toLowerCase()

Description: Converts all characters in the string to lowercase.

String str = "The Key To Success";


String lower = str.toLowerCase();
System.out.println(lower);

O/P:
the key to
success
6. toUpperCase()

Description: Converts all characters in the string to


uppercase.

O/P:
String str = "Hello, World!"; HELLO, WORLD!

String upper = str.toUpperCase();


7. trim()

Description: trim() in Java is a method that removes


leading and trailing whitespace from a string.

String strWithSpaces = " coding Ninjas ";


String trimmed = strWithSpaces.trim();

O/P:
coding Ninjas
8. replace(char oldChar, char
newChar)
Description: Replaces all occurrences of the specified old character
with the specified new character.

String str = "Javatutorial";


String replaced = str.replace('a', 'b');

O/P:
Jbvbtutoribl
9. replaceAll(String regex, String
replacement)
Description: Replaces each substring of this string that matches the
given regular expression with the given replacement.

String str = "This is a string";


String replacedAll = str.replaceAll("a", "the");

O/P:
This is the string
10.split(String regex)
Description: Splits this string around matches of the given regular
expression.

String str = "Yes, You Can Do It!";


String[] parts = str.split(", ");

O/P:
["Yes", "You Can Do It!"]
11. equals(Object another)

Description: Compares this string to the specified object.

String dt1 = "12-3-18";


String dt2 = "12-3-18";
String dt3 = "12-5-18";
System.out.println(dt1.equals(dt2));
System.out.println(dt2.equals(dt3));

O/P:
true
false
12. equalsIgnoreCase(String
anotherString)
Description: Compares this String to another String, ignoring case
considerations.

String str1= "STRING";


String str2= "STriNG";
System.out.println(str1.equalsIgnoreCase(str2));

O/P:
true
13. contains(CharSequence s)
Description: Returns true if, and only if, this string contains the
specified sequence of char values.

String str = "TestString";


System.out.println(str.contains("String"));

O/P:
true
14. indexOf(String str)
Description: Returns the index within this string of the first
occurrence of the specified substring.

String str = "abcd";


System.out.println(str.indexOf(‘b’));

O/P:
1
15. lastIndexOf(String str)
Description: Returns the index within this string of the last
occurrence of the specified substring.

String str = "WELCOME";


System.out.println(str.lastIndexOf("E"));

O/P:
5
16. startsWith(String prefix)

Description: Tests if this string starts with the specified prefix.

String str = "abcdef";


System.out.println(str.startsWith("abc"
));

O/P:
true
17. endsWith(String suffix)
Description: Tests if this string ends with the specified suffix.

String str = "Exercise";


System.out.println(str.endsWith("se"));

O/P:
true
18. compareTo(String anotherString)
Description:Compares two strings lexicographically.

String str = "This is exercise 1";


String str2 = "This is exercise 1";
System.out.println(str.compareTo(str2));

O/P:
0
19. valueOf(int i)
Description: It is used to convert any data type, such as int, double,
char, or char array, to its string representation by creating a new
String object.

String numStr = 123

String.valueOf(123);
“123”
O/P:
123
20. isEmpty()

Description: Returns true if, and only if, length() is 0.

String emptyStr = "";


System.out.println(emptyStr.isEmpty());

O/P:
true
04
Solving industry
level problems on
strings
Strings :

1. Reverse a String
2. Valid Palindrome (Single Word)
3. Find the Index of the First Occurrence
in a String
4. Valid Anagram
5. Reverse Words in a String
Reverse a String
https://leetcode.com/problems/reverse-string/description/

Write a program to reverse a given string.


The reversed string should have all
characters in the opposite order. The
function should handle strings of varying
lengths, including empty strings and
single-character strings.
Reverse a String
https://leetcode.com/problems/reverse-string/description/

Test Case 1:
Input: s = "hello"
Output: "olleh"

Test Case 2:
Input: s = "abcd"
Output: "dcba"
Reverse a String

Approach 1: Iterative Method (Using a Character Array)


● Convert the string into a character array.
● Initialize two pointers, start at the beginning and end at
the last index of the array.
● Swap the characters at start and end.
Reverse a String
● Increment start and decrement end until they
meet.
● Convert the character array back to a string
and return it.
Time complexity : O(n) (Single traversal of the
array)
Space complexity : O(n) (Extra space for the
character array)
Reverse a String

Function reverseString(s):
Convert s to a character array arr
Initialize start = 0 and end = length
of arr - 1
While start < end:
Swap arr[start] and arr[end]
Increment start and decrement end
Return arr as a string
Reverse a String

public static String


reverseString(String s) {
char[] arr = s.toCharArray();
int start = 0, end = arr.length -
1;
while (start < end) {
char temp = arr[start];
Reverse a String

arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
return new String(arr);
}
Reverse a String
Function
Approach 4 :Using StringBuilder's reverseString(s):
Reverse Method Create a
StringBuilder object
● Create a StringBuilder from s
object from the string. Reverse the
StringBuilder
● Use the reverse() method Return the reversed
of StringBuilder. StringBuilder as a
string
Reverse a String

● Convert the StringBuilder back to a string and return it.


Time complexity : O(n)((Reversing the string internally)
Space complexity : O(n)(Extra space for StringBuilder)
Reverse a String

public static String reverseString(String s)


{
return new
StringBuilder(s).reverse().toString();
}
Valid Palindrome (Single Word)
https://leetcode.com/problems/valid-palindrome/description

Problem Statement : Given a single word


s, determine if it is a palindrome. A
string is a palindrome if it reads the
same forward and backward, ignoring case.
Test Case 1:
Input:
Valid Palindrome (Single Word)
https://leetcode.com/problems/valid-palindrome/description

s = "Level"
Output:
true
Explanation:
Ignoring case, the word "Level" reads the
same backward, so it is a palindrome.
Valid Palindrome (Single Word)

Approach 1: Two-Pointer Technique


● Convert the string to lowercase for case insensitivity.

● Use two pointers:


○ left starting at the beginning of the string.

○ right starting at the end of the string.


Valid Palindrome (Single Word)

● Compare the characters at left and right. If they differ,


return false.
● Increment left and decrement right to move towards
the center.
● If the entire string is traversed without mismatches,
return true.
Time Complexity: O(n) (Where n is the length of the word).
Space Complexity: O(1) (No extra space used).
Valid Palindrome (Single Word)
Function isPalindrome(s):
Convert s to lowercase
Initialize left = 0, right = length of
s - 1
While left < right:
If s[left] != s[right]:
Return false
Increment left and decrement right
Return true
Valid Palindrome (Single Word)

public static boolean


isPalindrome(String s) {
s = s.toLowerCase();
int left = 0, right = s.length() -
1;

while (left < right) {


Valid Palindrome (Single Word)

}
left++;
right--;
}
return true;
}
Valid Palindrome (Single Word)

Approach 2: Reverse the String


● Convert the string to lowercase.

● Reverse the string.


● Compare the original string with the reversed string. If they
are the same, return true. Otherwise, return false.
Time Complexity: O(n) (Reversing and comparing the string).
Space Complexity: O(n) (For the reversed string).
Valid Palindrome (Single Word)
Function isPalindrome(s):
Convert s to lowercase
Reverse the string
If original string equals reversed
string:
Return true
Else:
Return false
Valid Palindrome (Single Word)
public static boolean
isPalindrome(String s) {
s = s.toLowerCase();
String reversed = new
StringBuilder(s).reverse().toString(
);
return s.equals(reversed);
}
Find the Index of the First Occurrence in a String
https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/description/

Problem Statement:
You are given two strings:
A main string haystack.
A target string needle.
Your task is to find the index of the first
occurrence of needle in haystack. If needle
does not exist in haystack, return -1.
Find the Index of the First Occurrence in a String
https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/description/

Test Cases:
Test Case 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Explanation: The substring "ll" starts at
index 2.
Find the Index of the First Occurrence in a String

Approach 1: Brute Force


● Iterate through the string haystack from 0 to n -
m, where n is the length of haystack and m is the
length of needle.
● At each position, compare the substring of length
m in haystack starting at the current index with
needle.
Find the Index of the First Occurrence in a String

● If they match, return the current index.


● If no match is found after traversing haystack,
return -1.
Time Complexity: Worst Case: O(n * m) (n = length of
haystack, m = length of needle).
Space Complexity: O(1) (No extra space used).
Find the Index of the First Occurrence in a String
Function findIndex(haystack, needle):
Let n = length of haystack
Let m = length of needle

For i = 0 to n - m:
If haystack.substring(i, i + m) == needle:
Return i

Return -1
Find the Index of the First Occurrence in a String

public static int findIndex(String


haystack, String needle) {
int n = haystack.length();
int m = needle.length();
Find the Index of the First Occurrence in a String

for (int i = 0; i <= n - m; i++) {


if (haystack.substring(i, i +
m).equals(needle)) {
return i;
}
}
return -1;
}
Find the Index of the First Occurrence in a String

Approach 2: Using Built-in Method


● Use the indexOf() method of the String class in Java.

● This method searches for the first occurrence of needle


in haystack.
● If found, it returns the index; otherwise, it returns -1.
Time Complexity: O(n) (optimized internal implementation).
Space Complexity: O(1)
Find the Index of the First Occurrence in a String

Function findIndex(haystack, needle):


Return haystack.indexOf(needle)
Find the Index of the First Occurrence in a String

public static int


findIndex(String haystack,
String needle) {
return
haystack.indexOf(needle);
}
Valid Anagram
https://leetcode.com/problems/valid-anagram/description/

Problem Statement:
Determine if two given strings, s and
t, are anagrams of each other.
Two strings are considered anagrams
if they contain the same characters
with the same frequency.
Valid Anagram
https://leetcode.com/problems/valid-anagram/description/

Examples
Input: s = "listen", t = "silent"
Output: true
Explanation: Both strings contain
the same characters with the same
frequency.
Valid Anagram

Approach 1: Sorting-Based
● Sort both strings.

● Compare if the sorted versions are identical.


Time Complexity: O(n log n) (sorting).
Space Complexity: O(n) (array storage).
Valid Anagram

Sort both strings s and t.


If sorted(s) == sorted(t):
Return true
Else:
Return false
Valid Anagram
public boolean isAnagram(String
s, String t) {
if (s.length() != t.length())
return false;

char[] arr1 =
s.toCharArray();
Valid Anagram

char[] arr2 = t.toCharArray();


Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1,
arr2);
}
Valid Anagram

Approach 2: Frequency Count Using Array


● Use an integer array of size 26 to store the frequency of
characters in s and t.
● Increment counts for characters in s and decrement for t.
● Check if all counts are zero.
Time Complexity: O(n) (traverse both strings once).
Space Complexity: O(1) (fixed-size array for 26 characters).
Valid Anagram

If lengths of s and t differ:


Return false
Create an array of size 26.
For each character in s:
Increment its corresponding count.
For each character in t:
Decrement its corresponding count.
If any count is non-zero:
Return false
Return true
Valid Anagram
public boolean isAnagram(String s,
String t) {
if (s.length() != t.length())
return false;
int[] counts = new int[26];
for (int i = 0; i < s.length();
i++) {
counts[s.charAt(i) - 'a']++;
Valid Anagram

counts[t.charAt(i) - 'a']--;
}
for (int count : counts)
if (count != 0) return
false;
return true;
}
Reverse Words in a String
https://leetcode.com/problems/reverse-words-in-a-string/description/

Problem Statement:
Given a string s, you need to reverse the
order of words in the string. A word is
defined as a sequence of non-space
characters. The reversed string should not
contain leading or trailing spaces, and
each word should be separated by exactly
one space.
Reverse Words in a String
https://leetcode.com/problems/reverse-words-in-a-string/description/

Example 1:
Input: "the sky is blue"
Output: "blue is sky the"
Example 2:
Input: " hello world "
Output: "world hello"
Reverse Words in a String

Approach 1: Two-Pointer Technique


In this approach, we first split the string into words,
reverse the words, and then join them back into a single
string.
Steps:
● Trim any leading or trailing spaces from the string.
Reverse Words in a String

● Split the string into words by spaces.


● Reverse the list of words.
● Join the words back together with a single space between
them.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n) due to storing words in an array and
the result.
Reverse Words in a String

function reverseWords(s):
# Step 1: Trim the string to remove
leading and trailing spaces
s = trim(s)
# Step 2: Split the string into words
based on spaces
words = split(s, " ")
Reverse Words in a String

# Step 3: Reverse the list of words


words = reverse(words)
# Step 4: Join the words back with a
single space
result = join(words, " ")
# Return the reversed sentence
return result
Reverse Words in a String

public static String


reverseWords(String s) {
// Trim leading and trailing spaces
s = s.trim();
// Split the string by spaces
String[] words = s.split("\\s+");
// Reverse the words
Reverse Words in a String

StringBuilder result = new StringBuilder();


for (int i = words.length - 1; i >= 0; i--
) {
result.append(words[i]);
if (i != 0) {
result.append(" ");
}
}
return result.toString();
}
Reverse Words in a String

Approach 2: In-place Reversal


This approach avoids the use of extra space for storing
words and directly manipulates the string in-place.
Steps:

● Reverse the entire string.


Reverse Words in a String

● Reverse each word individually within the


string.
● The result will be the words in reversed
order without using extra space.
Time Complexity: O(n)
Space Complexity: O(1) (no extra space used).
Reverse Words in a String

function reverseWords(s):
# Step 1: Reverse the entire
string
s = reverse(s)
# Step 2: Reverse each word
start = 0
Reverse Words in a String

for i in range(len(s)):
if s[i] == " " or i == len(s) - 1:
# Reverse the word between
start and i
reverse(s, start, i)
start = i + 1
# Step 3: Return the reversed string
return s
Reverse Words in a String

public static String


reverseWords(String s) {
// Step 1: Reverse the entire
string
s = new
StringBuilder(s).reverse().toString();
Reverse Words in a String

// Step 2: Reverse each word


int start = 0;
StringBuilder result = new
StringBuilder();
Reverse Words in a String
for (int i = 0; i <=
s.length(); i++) {
if (i == s.length() ||
s.charAt(i) == ' ') {
// Reverse the word
result.append(new
StringBuilder(s.substring(start,
i)).reverse().toString());
Reverse Words in a String

if (i < s.length())
result.append(" ");
start = i + 1;
}
}
return
result.toString().trim();
}
THANK YOU
iGenuine

inprotected.com

You might also like