Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Strings in Java :
String Methods
1. int length(): Returns the number of characters in the String.
"GeeksforGeeks".length(); // returns 13
2.
3. Char charAt(int i): Returns the character at ith index.
"GeeksforGeeks".charAt(3); // returns ‘k’
4.
5. String substring (int i): Return the substring from the ith index
character to end.
"GeeksforGeeks".substring(3); // returns “ksforGeeks”
6. String substring (int i, int j): Returns the substring from i to j-1
index.
"GeeksforGeeks".substring(2, 5); // returns “eks”
7. String concat( String str): Concatenates specified string to the end
of this string.
String s1 = ”Geeks”;
String s2 = ”forGeeks”;
String output = s1.concat(s2); // returns “GeeksforGeeks”
8. int indexOf (String s): Returns the index within the string of the
first occurrence of the specified string.
String s = ”Learn Share Learn”;
int output = s.indexOf(“Share”); // returns 6
9. int indexOf (String s, int i): Returns the index within the string of
the first occurrence of the specified string, starting at the specified
index.
String s = ”Learn Share Learn”;
int output = s.indexOf("ea",3);// returns 13
10. Int lastIndexOf( String s): Returns the index within the string of the
last occurrence of the specified string.
String s = ”Learn Share Learn”;
int output = s.lastIndexOf("a"); // returns 14
11. boolean equals( Object otherObj): Compares this string to the
specified object.
Boolean out = “Geeks”.equals(“Geeks”); // returns true
Boolean out = “Geeks”.equals(“geeks”); // returns false
12. boolean equalsIgnoreCase (String anotherString): Compares
string to another string, ignoring case considerations.
Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true
Boolean out = “Geeks”.equalsIgnoreCase(“geeks”); // returns true
13. int compareTo( String anotherString): Compares two string
lexicographically.
int out = s1.compareTo(s2); // where s1 ans s2 are
// strings to be compared
Note- In this case, it will not consider case of a letter (it will ignore
whether it is uppercase or lowercase).
15. String toLowerCase(): Converts all the characters in the String to
lower case.
String word1 = “HeLLo”;
String word3 = word1.toLowerCase(); // returns “hello"
16. String toUpperCase(): Converts all the characters in the String to
upper case.
String word1 = “HeLLo”;
String word2 = word1.toUpperCase(); // returns “HELLO”
17. String trim(): Returns the copy of the String, by removing
whitespaces at both ends. It does not affect whitespaces in the
middle.
String word1 = “ Learn Share Learn “;
String word2 = word1.trim(); // returns “Learn Share Learn”
18. String replace (char oldChar, char newChar): Returns new string
by replacing all occurrences of oldChar with newChar.
String s1 = “feeksforfeeks“;
String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // returns “geeksgorgeeks”
Note:- s1 is still feeksforfeeks and s2 is geeksgorgeeks
Program to illustrate all string methods:
Output:
two
Java program to swap first and last
characters of words in a sentence
Write a Java Program to Swap first and last character of words in a
Sentence as mentioned in the example?
Examples:
Input : geeks for geeks
Output :seekg rof seekg
Approach:As mentioned in the example we have to replace first and last
character of word and keep rest of the alphabets as it is.
First we have to split the String into String[] array. We have to split
the String where we found – symbol.
Input : 10e5.4
Output : false
Output:
abc is not a valid integer number
1234 is a valid integer number
Below are other short-hands regular expression for an integer number
[+-]?[0-9]+
[+-]?\d\d*
[+-]?\d+
Check if a given string is a valid floating point number
For floating point number : Below is the regular definition for a floating
point number.
sign -> + | - | epsilon
digit -> 0 | 1 | .... | 9
digits -> digit digit*
optional_fraction -> . digits | epsilon
optional_exponent -> ((E | e) (+ | - | epsilon) digits) | epsilon
num -> sign digits optional_fraction optional_exponent
Hence one of the regular expression for a floating number is
[+-]?[0-9]+(\.[0-9]+)?([Ee][+-]?[0-9]+)?
Output:
10e5.4 is not a valid float number
2e10 is a valid float number
Below is other short-hand regular expression for a float number
[+-]?\d+(\.\d+)?([Ee][+-]?\d+)?
Output:
geeksforgeeks to Welcome
Programming Java love I
Output:
Output:
Input : s1 = "geeksforgeeks"
s2 = ""
Output : s2 = "geeksforgeeks"
Iterative :
Copy every character from s1 to s2 starting from index = 0 and in each
call increase the index by 1 until s1 doesn’t reach to end;
Pangram Checking
Given a string check if it is Pangram or not. A pangram is a sentence
containing every letter in the English Alphabet.
Examples : The quick brown fox jumps over the lazy dog ” is a Pangram
[Contains all the characters from ‘a’ to ‘z’]
“The quick brown fox jumps over the dog” is not a Pangram [Doesn’t
contains all the characters from ‘a’ to ‘z’, as ‘l’, ‘z’, ‘y’ are missing]
We create a mark[] array of Boolean type. We iterate through all the
characters of our string and whenever we see a character we mark it.
Lowercase and Uppercase are considered the same. So ‘A’ and ‘a’ are
marked in index 0 and similarly ‘Z’ and ‘z’ are marked in index 25.
After iterating through all the characters we check whether all the
characters are marked or not. If not then return false as this is not a
pangram else return true.
// Java Program to illustrate Pangram
class GFG
{
// Returns true if the string
// is pangram else false
public static boolean checkPangram (String str)
{
// Create a hash table to mark the
// characters present in the string
// By default all the elements of
// mark would be false.
boolean[] mark = new boolean[26];
// For indexing in mark[]
int index = 0;
// Traverse all characters
for (int i = 0; i < str.length(); i++)
{
// If uppercase character, subtract 'A'
// to find index.
if ('A' <= str.charAt(i) &&
str.charAt(i) <= 'Z')
index = str.charAt(i) - 'A';
// If lowercase character, subtract 'a'
// to find index.
else if('a' <= str.charAt(i) &&
str.charAt(i) <= 'z')
index = str.charAt(i) - 'a';
// Mark current character
mark[index] = true;
}
// Return false if any character is unmarked
for (int i = 0; i <= 25; i++)
if (mark[i] == false)
return (false);
// If all characters were present
return (true);
}
// Driver Code
public static void main(String[] args)
{
String str = "The quick brown fox jumps over the lazy
dog";
if (checkPangram(str) == true)
System.out.print(str + " is a pangram.");
else
System.out.print(str+ " is not a pangram.");
}
}
Output :
"The quick brown fox jumps over the lazy dog"
is a pangram
Time Complexity: O(n), where n is the length of our string
Auxiliary Space – O(1)
Input: aaabc
Output: abaca
Input: aaabb
Output: ababa
Input: aa
Output: Not Possible
Input: aaaabc
Output: Not Possible
Prerequisite : priority_queue.
The idea is to put the highest frequency character first (a greedy
approach). We use a priority queue (Or Binary Max Heap) and put all
characters and ordered by their frequencies (highest frequency
character at root). We one by one take the highest frequency character
from the heap and add it to result. After we add, we decrease the
frequency of the character and we temporarily move this character out
of priority queue so that it is not picked next time.
We have to follow the step to solve this problem, they are:
1. Build a Priority_queue or max_heap, pq that stores characters and
their frequencies.
…… Priority_queue or max_heap is built on the bases of the frequency of
character.
2. Create a temporary Key that will be used as the previously visited
element (the previous element in the resultant string. Initialize it { char =
‘#’ , freq = ‘-1’ }
3. While pq is not empty.
….. Pop an element and add it to the result.
….. Decrease frequency of the popped element by ‘1’
….. Push the previous element back into the priority_queue if it’s
frequency > ‘0’
….. Make the current element as the previous element for the next
iteration.
4. If the length of the resultant string and original, print “not possible”.
Else print result.
Below is the implementation of above idea
// Java program to rearrange characters in a string
// so that no two adjacent characters are same.
import java.io.*;
import java.util.*;
class KeyComparator implements Comparator<Key> {
// Overriding compare()method of Comparator
public int compare(Key k1, Key k2)
{
if (k1.freq < k2.freq)
return 1;
else if (k1.freq > k2.freq)
return -1;
return 0;
}
}
class Key {
int freq; // store frequency of character
char ch;
Key(int val, char c)
{
freq = val;
ch = c;
}
}
class GFG {
static int MAX_CHAR = 26;
// Function to rearrange character of a string
// so that no char repeat twice
static void rearrangeString(String str)
{
int n = str.length();
// Store frequencies of all characters in string
int[] count = new int[MAX_CHAR];
for (int i = 0; i < n; i++)
count[str.charAt(i) - 'a']++;
// Insert all characters with their frequencies
// into a priority_queue
PriorityQueue<Key> pq = new PriorityQueue<>(new
KeyC
omparator());
for (char c = 'a'; c <= 'z'; c++) {
int val = c - 'a';
if (count[val] > 0)
pq.add(new Key(count[val], c));
}
// 'str' that will store resultant value
str = "" ;
// work as the previous visited element
// initial previous element be. ( '#' and
// it's frequency '-1' )
Key prev = new Key(-1, '#');
// traverse queue
while (pq.size() != 0) {
// pop top element from queue and add it
// to string.
Key k = pq.peek();
pq.poll();
str = str + k.ch;
// If frequency of previous character is
less
// than zero that means it is useless, we
// need not to push it
if (prev.freq > 0)
pq.add(prev);
// make current character as the previous
'char'
// decrease frequency by 'one'
(k.freq)--;
prev = k;
}
// If length of the resultant string and
original
// string is not same then string is not valid
if (n != str.length())
System.out.println(" Not valid String ");
else
System.out.println(str);
}
// Driver program to test above function
public static void main(String args[])
{
String str = "bbbaa" ;
rearrangeString(str);
}
}
Output:
babab
Time complexity : O(n)
Input : s = "gggg"
Output : Yes
Simple Way
To find whether string has all the same characters. Traverse the whole
string from index 1 and check whether that character matches with first
character of string or not. If yes, than match until string size. If no, than
break the loop.
// Java program to find whether the String
// has all same characters or not.
import java.io.*;
public class GFG{
static boolean allCharactersSame(String s)
{
int n = s.length();
for (int i = 1; i < n; i++)
if (s.charAt(i) != s.charAt(0))
return false;
return true;
}
// Driver code
static public void main (String[] args){
String s = "aaa";
if (allCharactersSame(s))
System.out.println("Yes");
else
System.out.println("No");
}
}
Output:
Yes
Input : 02364
Output : It is not a duck number.
Explanation: in 02364 there is a zero at the beginning of the number.
// Java Program to check whether a
// number is Duck Number or not.
import java.io.*;
class GFG
{
// Function to check whether
// the given number is duck number or not.
static int check_duck( String num)
{
// Length of the number(number of digits)
int len = num.length();
int count_zero = 0 ;
char ch;
for(int i = 1;i < len ;i++)
{
// Checking for a digit whether it is a '0' or not
ch=num.charAt(i);
if(ch=='0')
count_zero++;
}
return count_zero ;
}
// Driver Method
public static void main(String args[])throws IOException
{
String num1 = "1023";
// extracting the first digit
char first_digit1 = num1.charAt(0);
// checking number1
if( check_duck(num1) > 0 && first_digit1 != '0')
System.out.println("It is a duck number");
else
System.out.println("It is not a duck number");
}
}
Output :
It is a duck number.
Input : 38
Output : 40
Input : 10
Output: 10
Approach:
Let’s round down the given number n to the nearest integer which ends
with 0 and store this value in a variable a.
a = (n / 10) * 10. So, the round up n (call it b) is b = a + 10.
If n – a > b – n then the answer is b otherwise the answer is a.
Below is the implementation of the above approach:
// JAVA Code for Round the given number
// to nearest multiple of 10
import java.util.*;
class GFG {
// function to round the number
static int round(int n)
{
// Smaller multiple
int a = (n / 10) * 10;
// Larger multiple
int b = a + 10;
// Return of closest of two
return (n - a > b - n)? b : a;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int n = 4722;
System.out.println(round(n));
}
}
Output:
4720
Character Counting Based Problems :
Count Uppercase, Lowercase, special
character and numeric values
Given a string, write a program to count the occurrence of Lowercase
characters, Uppercase characters, Special characters and Numeric
values.
Examples:
Input : #GeeKs01fOr@gEEks07
Output :
Upper case letters : 5
Lower case letters : 8
Numbers : 4
Special Characters : 2
Input : *GeEkS4GeEkS*
Output :
Upper case letters : 6
Lower case letters : 4
Numbers : 1
Special Characters : 2
Approach :
Step 1: Scan a string str from 0 to length-1.
Step 2: check one character at a time on the basis of ASCII values
if(str[i] >= 65 and str[i] =97 and str[i] =48 and str[i] <=57) number
else special character
step 3: Print all the counters.
Output:
Upper case letters: 5
Lower case letters : 8
Number : 4
Special characters : 2
Input : aaab
Output : ab
Explanation :
ab of length 2 is the smallest window
with highest number of distinct characters.
Above problem states that we have to find the smallest window that
contains all the distinct characters of the given string even if the smallest
string contains repeating elements.
For example, in “aabcbcdb”, the smallest string that contains all the
characters is “abcbcd”.
This problem reduces to Find the smallest window in a string containing
all characters of another string.
In that problem we find the smallest window that contains all the
characters of given pattern.
1- Count all distinct characters in given string.
2- Now follow the algorithm discussed in below post.
https://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-
containing-all-characters-of-another-string/
We basically maintain a window of characters. Whenever the window
contains all characters of given string, we shrink the window from left
side to remove extra characters and then compare its length with
smallest window fount so far.
// Java program to find the smallest window containing
// all characters of a pattern.
import java.util.Arrays;
public class GFG {
static final int MAX_CHARS = 256;
// Function to find smallest window containing
// all distinct characters
static String findSubString(String str)
{
int n = str.length();
// Count all distinct characters.
int dist_count = 0;
boolean[] visited = new boolean[MAX_CHARS];
Arrays.fill(visited, false);
for (int i=0; i<n; i++)
{
if (visited[str.charAt(i)] == false)
{
visited[str.charAt(i)] = true;
dist_count++;
}
}
// Now follow the algorithm discussed in below
// post. We basically maintain a window of characters
// that contains all characters of given string.
// https://www.geeksforgeeks.org/find-the-smallest-
window-in-a-string-containing-all-characters-of-another-
string/
int start = 0, start_index = -1;
int min_len = Integer.MAX_VALUE;
int count = 0;
int[] curr_count = new int[MAX_CHARS];
for (int j=0; j<n; j++)
{
// Count occurrence of characters of string
curr_count[str.charAt(j)]++;
// If any distinct character matched,
// then increment count
if (curr_count[str.charAt(j)] == 1 )
count++;
// if all the characters are matched
if (count == dist_count)
{
// Try to minimize the window i.e., check if
// any character is occurring more no. of
times
// than its occurrence in pattern, if yes
// then remove it from starting and also
remove
// the useless characters.
while (curr_count[str.charAt(start)] > 1)
{
if (curr_count[str.charAt(start)] > 1)
curr_count[str.charAt(start)]--;
start++;
}
// Update window size
int len_window = j - start + 1;
if (min_len > len_window)
{
min_len = len_window;
start_index = start;
}
}
}
// Return substring starting from start_index
// and length min_len
return str.substring(start_index,
start_index+min_len);
}
// Driver code
public static void main(String args[])
{
String str = "aabcbcdbca";
System.out.println("Smallest window containing all
distinct"
+ " characters is " + findSubString(str));
}
}
Output:
Smallest window containing all distinct characters is
dbca
Input: aba, k = 2
Output: 3
Possible substrings are {"ab", "ba", "aba"}
Input: aa, k = 1
Output: 3
Possible substrings are {"a", "a", "aa"}
Method 1 (Brute Force)
No of words : 5
Time complexity: O(n)
Steps:
1. Extract each word from string.
2. For each word, check if it is in word array(by creating set/map). If
present, increment result.
Below is the Java implementation of above steps
// Java program to count number
// of words present in a string
import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test
{
static int countOccurrence(String[] word, String str)
{
// counter
int counter = 0;
// for extracting words
Pattern p = Pattern.compile("[a-zA-Z]+");
Matcher m = p.matcher(str);
// HashSet for quick check whether
// a word in str present in word[] or not
HashSet<String> hs = new HashSet<String>();
for (String string : word) {
hs.add(string);
}
while(m.find())
{
if(hs.contains(m.group()))
counter++;
}
return counter;
}
public static void main(String[] args)
{
String word[] = { "welcome", "to", "geeks", "portal"};
String str = "geeksforgeeks is a computer science
portal for geeks.";
System.out.println(countOccurrence(word,str));
}
}
Output:
2
Output:
skeeG rof skeeG
This can be done in more simpler way by using the property of the “%s
format specifier” .
Property: %s will get all the values until it gets NULL i.e. ‘\0’.
Example: char String[] = “I AM A GEEK” is stored as shown in the image
below :
Step 3: At the end, the loop ends when it reaches the first character, so
print the remaining characters, it will be printed the first NULL character,
hence the first word will be pprinted.
Program:
// Java program to reverse a string using recursion
class StringReverse
{
/* Function to print reverse of the passed string */
void reverse(String str)
{
if ((str==null)||(str.length() <= 1))
System.out.println(str);
else
{
System.out.print(str.charAt(str.length()-1));
reverse(str.substring(0,str.length()-1));
}
}
/* Driver program to test above function */
public static void main(String[] args)
{
String str = "Geeks for Geeks";
StringReverse obj = new StringReverse();
obj.reverse(str);
}
}
Output:
skeeG rof skeeG
Time Complexity: O(n)
Input : s = "aaaa"
Output : 1
The idea is based on below post.
A Program to check if strings are rotations of each other or not
Output:
3
Time Complexity: O(n2)
Input : s = "qwertyu"
d=2
Output : Left rotation : "ertyuqw"
Right rotation : "yuqwert"
A Simple Solution is to use a temporary string to do rotations. For left
rotation, first copy last n-d characters, then copy first d characters in
order to the temporary string. For right rotation, first copy last d
characters, then copy n-d characters.
Can we do both rotations in-place and O(n) time?
The idea is based on reversal algorithm for rotation.
// Left rotate string s by d (Assuming d <= n)leftRotate(s, d)
reverse(s, 0, d-1); // Reverse substring s[0..d-1]
reverse(s, d, n-1); // Reverse substring s[d..n-1]
reverse(s, 0, n-1); // Reverse whole string.
Output:
I am from GeeksforGeeks
Input : geeksforgeeks
Output : eeeefggkkorss
// Java program to sort a string of characters
import java.util.Arrays;
class GFG {
// function to print string in sorted order
static void sortString(String str) {
char []arr = str.toCharArray();
Arrays.sort(arr);
System.out.print(String.valueOf(arr));
}
// Driver program to test above function
public static void main(String[] args) {
String s = "geeksforgeeks";
sortString(s);
}
}
Output:
eeeefggkkorss
Time Complexity: O(n log n), where n is the length of string.
An efficient approach will be to observe first that there can be a total of
26 unique characters only. So, we can store the count of occurrences of
all the characters from ‘a’ to ‘z’ in a hashed array. The first index of the
hashed array will represent character ‘a’, second will represent ‘b’ and
so on. Finally, we will simply traverse the hashed array and print the
characters from ‘a’ to ‘z’ the number of times they occurred in input
string.
Below is the implementation of above idea:
// Java program to sort
// a string of characters
import java.util.Arrays;
import java.util.Collections;
class GFG
{
// Method to sort a
// string alphabetically
public static String sortString(String inputString)
{
// convert input
// string to char array
char tempArray[] =
inputString.toCharArray();
// sort tempArray
Arrays.sort(tempArray);
// return new sorted string
return new String(tempArray);
}
// Driver Code
public static void main(String[] args)
{
String inputString = "geeksforgeeks";
System.out.println(sortString(inputString));
}
}
Output:
eeeefggkkorss
Time Complexity: O( n ), where n is the length of input string.
Auxiliary Space: O( 1 ).
Input : nupursingh
Output : uusrpnnihg
Input : geeksforgeeks
Output : ssrokkggfeeee
// Java program to sort a string in descending
// order using library function
import java.util.*;
class GFG
{
static void descOrder(char[] s)
{
Arrays.sort(s);
reverse(s);
}
static void reverse(char[] a)
{
int i, n = a.length;
char t;
for (i = 0; i < n / 2; i++)
{
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
// Driver code
public static void main(String[] args)
{
char[] s = "geeksforgeeks".toCharArray();
descOrder(s); // function call
System.out.println(String.valueOf(s));
}
}
Output:
ssrokkggfeeee
The time complexity is : O(n log n)
An efficient approach will be to observe first that there can be a total of
26 unique characters only. So, we can store the count of occurrences of
all the characters from ‘a’ to ‘z’ in a hashed array. The first index of the
hashed array will represent character ‘a’, second will represent ‘b’ and
so on. Finally, we will simply traverse the hashed array and print the
characters from ‘z’ to ‘a’ the number of times they occurred in input
string.
Below is the implementation of above idea:
// Java program to sort a string of characters
// in descending order
class GFG
{
static int MAX_CHAR = 26;
// function to print string in sorted order
static void sortString(String str)
{
// Hash array to keep count of characters.
// Initially count of all charters is
// initialized to zero.
int charCount[] = new int[MAX_CHAR];
// Traverse string and increment
// count of characters
// 'a'-'a' will be 0, 'b'-'a' will be 1,
for (int i = 0; i < str.length(); i++)
{
// so for location of character in count
// array we wil do str[i]-'a'.
charCount[str.charAt(i) - 'a']++;
}
// Traverse the hash array and print
// characters
for (int i = MAX_CHAR - 1; i >= 0; i--)
{
for (int j = 0; j < charCount[i]; j++)
{
System.out.print((char) ('a' + i));
}
}
}
// Driver code
public static void main(String[] args)
{
String s = "alkasingh";
sortString(s);
}
}
Output:
snlkihgaa
Time Complexity: O( n ), where n is the length of input string.
Auxiliary Space: O( 1 ).