w3resource

Java: Check whether the first instance of a given character is immediately followed by the same character in a given string


98. Check Repeated Character at First Instance

Write a Java program to check whether the first instance of a given character is immediately followed by the same character in a given string.

Visual Presentation:

Java String Exercises: Check whether the first instance of a given character is immediately followed by the same character in a given string


Sample Solution:

Java Code:

import java.util.*;

// Define a class named Main
public class Main {
  
  // Method to check if 'z' appears twice in succession in the string
  boolean appearTwice(String stng) {
    int i = stng.indexOf("z"); // Get the index of the first occurrence of 'z'
    if (i == -1) return false; // If 'z' is not found, return false
    
    if (i + 1 >= stng.length()) return false; // If 'z' is at the end of the string, return false
    
    // Check if the character after the first 'z' is also 'z'
    return stng.substring(i + 1, i + 2).equals("z");
  }

  // Main method to execute the program
  public static void main(String[] args) {
    Main m = new Main(); // Create an instance of the Main class

    String str1 = "fizzez"; // Given string
    // Display the given string and whether 'z' appears twice respectively
    System.out.println("The given string is: " + str1);
    System.out.println("Is 'z' appear twice respectively? " + m.appearTwice(str1));
  }
}

Sample Output:

The given string is: fizzez
Is 'z' appear twice respectively? true

Flowchart:

Flowchart: Java String Exercises - CCheck whether the first instance of a given character is immediately followed by the same character in a given string



For more Practice: Solve these Related Problems:

  • Write a Java program to determine if the first occurrence of a target character is immediately repeated in the string.
  • Write a Java program to check if the first instance of a given letter is directly duplicated.
  • Write a Java program to verify if the first appearance of a specified character is immediately followed by the same character.
  • Write a Java program to locate the first instance of a character and test if the subsequent character is identical.

Go to:


PREV : Chars at Indices 0-2, 5-7, etc.
NEXT : Even Index Characters Only.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.