You are on page 1of 14

Searching For Characters and Substring in a String in Java

A) Searching a Character in the String

1. // Java Program to Illustrate to Find a Character


// in the String

// Importing required classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{

// String in which a character to be searched.


String str
= "GeeksforGeeks is a computer science portal";

// Returns index of first occurrence of character.


int firstIndex = str.indexOf('s');
System.out.println("First occurrence of char 's'"
+ " is found at : "
+ firstIndex);

// Returns index of last occurrence specified


// character.
int lastIndex = str.lastIndexOf('s');
System.out.println("Last occurrence of char 's' is"
+ " found at : " + lastIndex);

// Index of the first occurrence of specified char


// after the specified index if found.
int first_in = str.indexOf('s', 10);
System.out.println("First occurrence of char 's'"
+ " after index 10 : "
+ first_in);

int last_in = str.lastIndexOf('s', 20);


System.out.println("Last occurrence of char 's'"
+ " after index 20 is : "
+ last_in);

// gives ASCII value of character at location 20


int char_at = str.charAt(20);
System.out.println("Character at location 20: "
+ char_at);

// Note: If we uncomment it will throw


// StringIndexOutOfBoundsException
// char_at = str.charAt(50);
}
}

Output
First occurrence of char 's' is found at : 4
Last occurrence of char 's' is found at : 28
First occurrence of char 's' after index 10 : 12
Last occurrence of char 's' after index 20 is : 15
Character at location 20: 111

2.Searching Substring in the String

// Java Program to illustrate to Find a Substring


// in the String

// Importing required classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{

// A string in which a substring


// is to be searched
String str
= "GeeksforGeeks is a computer science portal";

// Returns index of first occurrence of substring


int firstIndex = str.indexOf("Geeks");

System.out.println("First occurrence of char Geeks"


+ " is found at : "
+ firstIndex);

// Returns index of last occurrence


int lastIndex = str.lastIndexOf("Geeks");
System.out.println(
"Last occurrence of char Geeks is"
+ " found at : " + lastIndex);

// Index of the first occurrence


// after the specified index if found
int first_in = str.indexOf("Geeks", 10);
System.out.println("First occurrence of char Geeks"
+ " after index 10 : "
+ first_in);

int last_in = str.lastIndexOf("Geeks", 20);


System.out.println("Last occurrence of char Geeks "
+ "after index 20 is : "
+ last_in);
}
}

Output
First occurrence of char Geeks is found at : 0
Last occurrence of char Geeks is found at : 8
First occurrence of char Geeks after index 10 : -1
Last occurrence of char Geeks after index 20 is : 8
3. contains(CharSequence seq): It returns true if the string contains the specified
sequence of char values otherwise returns false. Its parameters specify the
sequence of characters to be searched and throw NullPointerException if seq is
null.

// Java Program to Illustrate How to Find a Substring


// in the String using contains() Method

// Importing required classes


import java.io.*;
import java.lang.*;

// Class
class GFG {

// Main driver method


public static void main(String[] args)
{
// String in which substring
// to be searched
String test = "software";

CharSequence seq = "soft";


boolean bool = test.contains(seq);
System.out.println("Found soft?: " + bool);

// Returns true substring if found.


boolean seqFound = test.contains("war");
System.out.println("Found war? " + seqFound);

// Returns true substring if found


// otherwise return false
boolean sqFound = test.contains("wr");
System.out.println("Found wr?: " + sqFound);
}
}

Output
Found soft?: true
Found war? true
Found wr?: false

4. Matching String Start and End

boolean startsWith(String str): Returns true if the string str exists at the
starting of the given string, else false.
boolean startsWith(String str, int indexNum): Returns true if the string str exists
at the starting of the index indexNum in the given string, else false.
boolean endsWith(String str): Returns true if the string str exists at the ending
of the given string, else false.

// Java Program to Match ofstart and endof a Substring

// Importing required classes


import java.io.*;

// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Input string in which substring
// is to be searched
String str
= "GeeksforGeeks is a computer science portal";

// Print and display commands


System.out.println(str.startsWith("Geek"));
System.out.println(str.startsWith("is", 14));
System.out.println(str.endsWith("port"));
}
}

SUBSTRINGS

1a)public class CountSubstrings {


public static int countSubstrings(String str, int n) {
int count = 0;
for (int i = 0; i <= str.length() - n; i++) {
String substring = str.substring(i, i + n);
// check if the current substring has length n
if (substring.length() == n) {
count++;
}
}
return count;
}

public static void main(String[] args) {


String str = "geeksforgeeks";
int n = 5;
System.out.println(countSubstrings(str, n));
}
}

Output
9

1b) // Java implementation of the approach


import java.util.*;

class GFG
{

// Function to return the count of


// possible sub-strings of length n
static int countSubStr(String str, int n)
{
int len = str.length();
return (len - n + 1);
}

// Driver code
public static void main(String args[])
{
String str = "geeksforgeeks";
int n = 5;

System.out.print(countSubStr(str, n));
}
}

// This code is contributed by mohit kumar 29

Output
9

2. Given a string str and a character X. The task is to find the total number of
sub-strings that contain the character X at least once.

// Java implementation of the approach


class GFG
{

// Function to return the count of


// required sub-strings
static int countSubStr(String str, int n, char x)
{
int res = 0, count = 0;
for (int i = 0; i < n; i++)
{
if (str.charAt(i) == x)
{

// Number of sub-strings from position


// of current x to the end of str
res += ((count + 1) * (n - i));

// To store the number of characters


// before x
count = 0;
}
else
count++;
}

return res;
}

// Driver code
public static void main(String[] args)
{
String str = "abcabc";
int n = str.length();
char x = 'c';

System.out.println(countSubStr(str, n, x));
}
}

// This code has been contributed by 29AjayKumar


3.Given a string str and Q queries. Every query consists of a number X, the task is
to print the Xth lexicographically smallest sub-string of the given string str.

// Java implementation of the approach


import java.util.*;

class GFG
{

// Function to pre-process the sub-strings


// in sorted order
static void pre_process(String substrings[],String s)
{
int n = s.length();

// Generate all substrings


int count = 0;
for (int i = 0; i < n; i++)
{
String dup = "";

// Iterate to find all sub-strings


for (int j = i; j < n; j++)
{
dup += s.charAt(j);

// Store the sub-string in the vector


substrings[count++] = dup;
}
}

// Sort the substrings lexicographically


int size = substrings.length;

for(int i = 0; i < size-1; i++) {


for (int j = i + 1; j < substrings.length; j++)
{
if(substrings[i].compareTo(substrings[j]) > 0)
{
String temp = substrings[i];
substrings[i] = substrings[j];
substrings[j] = temp;
}
}

//sort(substrings.begin(), substrings.end());
}
}

// Driver code
public static void main(String args[])
{
String s = "geek";

// To store all the sub-strings


String substrings[] = new String[10];
pre_process(substrings, s);

int queries[] = { 1, 5, 10 };
int q = queries.length;

// Perform queries
for (int i = 0; i < q; i++)
System.out.println(substrings[queries[i]-1]);

}
}

4. Maximum count of sub-strings of length K consisting of same characters

Examples:

Input: str = “aaacaabbaa”, k = 2


Output: 3
“aa” and “bb” are the only sub-strings of length 2 that consist of the same
characters.
“bb” appears only once as a sub-string of str whereas “aa” appears thrice (which is
the answer)

Input: str = “abab”, k = 2


Output: 0

// Java implementation of the approach


import java.util.*;
import java.lang.*;
import java.io.*;

class GFG
{

// Function to return the count


// of the required sub-strings
static int maxSubStrings(String s, int k)
{
int maxSubStr = 0, n = s.length();

// Iterate over all characters


for (int c = 0; c < 26; c++)
{
char ch = (char)((int)'a' + c);

// Count with current character


int curr = 0;
for (int i = 0; i <= n - k; i++)
{
if(s.charAt(i) != ch)
continue;
int cnt = 0;
while (i < n && s.charAt(i) == ch &&
cnt != k)
{
i++;
cnt++;
}
i--;

// If the substring has a length


// k then increment count with
// current character
if (cnt == k)
curr++;
}

// Update max count


maxSubStr = Math.max(maxSubStr, curr);
}
return maxSubStr;
}

// Driver Code
public static void main(String []args)
{
String s = "aaacaabbaa";
int k = 2;
System.out.println(maxSubStrings(s, k));
}
}

Output
3

5. // Java program to count number of


// substrings of s1 present in s2.
import java.util.*;

class GFG
{

static int countSubstrs(String s1,


String s2)
{
int ans = 0;

for (int i = 0; i < s1.length(); i++)


{

// s3 stores all substrings of s1


String s3 = "";
char[] s4 = s1.toCharArray();
for (int j = i; j < s1.length(); j++)
{
s3 += s4[j];

// check the presence of s3 in s2


if (s2.indexOf(s3) != -1)
ans++;
}
}
return ans;
}

// Driver code
public static void main(String[] args)
{
String s1 = "aab", s2 = "aaaab";
System.out.println(countSubstrs(s1, s2));
}
}

// This code is contributed by ChitraNayal

Output
6

6. Print all substring of a number without any conversion

// Java implementation
// of above approach
import java.util.*;
import java.lang.*;
import java.io.*;

class GFG
{
// Function to print the
// substrings of a number
static void printSubstrings(int n)
{
// Calculate the total
// number of digits
int s = (int)Math.log10(n);

// 0.5 has been added because


// of it will return double
// value like 99.556
int d = (int)(Math.pow(10, s) + 0.5);
int k = d;

while (n > 0)
{

// Print all the numbers


// from starting position
while (d > 0)
{
System.out.println(n / d);
d = d / 10;
}

// Update the no.


n = n % k;

// Update the no.of digits


k = k / 10;
d = k;
}
}

// Driver code
public static void main(String args[])
{
int n = 123;
printSubstrings(n);
}
}
Output:
1
12
123
2
23
3

7. Substring Reverse Pattern


Examples:

Input: str = “geeks”


Output:
geeks
*kee*
**e**
The reverse of “geeks” is “skeeg”
Replace the first and last characters with ‘*’ i.e. *kee*
Replace the second and second last character in the modified string i.e. **e**
And so on.

Input: str = “first”


Output:
first
*sri*
**r**

// Java program to print the required pattern


class GFG
{

// Function to print the required pattern


static void printPattern(char[] s, int n)
{
// Print the unmodified string
System.out.println(s);

// Reverse the string


int i = 0, j = n - 1;
while (i < j)
{
char c = s[i];
s[i] = s[j];
s[j] = c;
i++;
j--;
}

// Replace the first and last character


// by '*' then second and second last
// character and so on until the string
// has characters remaining
i = 0;
j = n - 1;
while (j - i > 1)
{
s[i] = s[j] = '*';
System.out.println(s);
i++;
j--;
}
}

// Driver Code
public static void main(String []args)
{
char[] s = "geeks".toCharArray();
int n = s.length;

printPattern(s, n);
}
}

// This code is contributed by Rituraj Jain

8. Count number of substrings with numeric value greater than X


Examples:

Input: S = "471", X = 47
Output: 2
Only the sub-strings "471" and "71"
satisfy the given conditions.

Input: S = "2222", X = 97
Output: 3
Valid strings are "222", "222" and "2222".

// Java implementation of the approach


import java.util.*;

class GFG
{
// Function that counts
// valid sub-strings
static int count(String S, int X)
{
int count = 0;
int N = S.length();
for (int i = 0; i < N; ++i)
{

// Only take those numbers


// that do not start with '0'.
if (S.charAt(i) != '0')
{
for (int len = 1;
(i + len) <= N; ++len)
{

// converting the sub-string


// starting from index 'i'
// and having length 'len' to
// int and checking if it is
// greater than X or not
int num = Integer.parseInt(S.substring(i, i + len));
if (num > X)
count++;
}
}
}
return count;
}

// Driver code
public static void main(String []args)
{
String S = "2222";
int X = 97;
System.out.println(count(S, X));
}
}

Output
3

9. Count all substrings having character K

Examples:

Input: str = “geeks”, K = ‘g’


Output: 5
“g”, “ge”, “gee”, “geek” and “geeks” are the valid substrings.
Input: str = “geeksforgeeks”, K = ‘k’
Output: 56

// Java implementation of the approach


import java.util.*;

class GFG
{

// Function to return the index of the


// next occurrence of character ch in str
// starting from the given index
static int nextOccurrence(String str, int n,
int start, char ch)
{
for (int i = start; i < n; i++)
{

// Return the index of the first


// occurrence of ch
if (str.charAt(i) == ch)
return i;
}

// No occurrence found
return -1;
}

// Function to return the count of all


// the substrings of str which contain
// the character ch at least one
static int countSubStr(String str,
int n, char ch)
{

// To store the count of valid substrings


int cnt = 0;

// Index of the first occurrence of ch in str


int j = nextOccurrence(str, n, 0, ch);
for (int i = 0; i < n; i++)
{
while (j != -1 && j < i)
{
j = nextOccurrence(str, n, j + 1, ch);
}

// No occurrence of ch after index i in str


if (j == -1)
break;

// Substrings starting at index i


// and ending at indices j, j+1, ..., n-1
// are all valid substring
cnt += (n - j);
}
return cnt;
}

// Driver code
static public void main ( String []arg)
{
String str = "geeksforgeeks";
int n = str.length();
char ch = 'k';

System.out.println(countSubStr(str, n, ch));
}
}

// This code is contributed by PrinciRaj1992

Output:
56

10. public class FibonacciIterative {


public static void main(String[] args) {
int n = 10; // Number of Fibonacci numbers to generate
System.out.println("Fibonacci Sequence (Iterative):");
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}

public static int fibonacci(int n) {


if (n <= 1) {
return n;
}
int prev = 0, curr = 1, next;
for (int i = 2; i <= n; i++) {
next = prev + curr;
prev = curr;
curr = next;
}
return curr;
}
}

You might also like