Write a java program to Check Characters in a String

Write a program to read a string and to test whether the first and last character is the same. The string is said to be valid if the 1st and last characters are the same. Else the string is said to be invalid.

Input and Output Format

  • Input consists of a string.
  • The output is a string saying characters are the same or not.

Refer sample output for formatting specifications

Sample Input 1:

the picture was great

Sample Output 1:

Valid

Sample Input 1:

this

Sample Output 1:

Invalid

Check Characters in a String in Java.

Following are the steps to check the equality of the first and last character in a sentence:

  • Input a string from the user.
  • Call checkForFirstAndLastChar() method with the input string.
  • Inside the method, break the string into tokens by using StringTokenizer.
  • Now, compare the character at 0th index to char at the last character, and if both are the same return 1 else return -1.
  • At last, based on the return value just prints valid and invalid.
 import java.util.Scanner;
import java.util.StringTokenizer;
public class Solution11
{
                public static void main(String[] args)
                    
                {
                	Scanner sc = new Scanner(System.in);
                	String s1 = sc.nextLine();
                    int n =  checkForFirstAndLastChar(s1);
                    if(n==0){
                    	System.out.println("Invalid");
                    	
                    }else{
                    	System.out.println("Valid");
                    }
                
                }
                public static int checkForFirstAndLastChar(String input)
                {
                                StringTokenizer t = new StringTokenizer(input," ");
                                String s = t.nextToken();
                                String s1 = " " ;
                                while(t.hasMoreTokens())
                                {
                                                s1 = t.nextToken();
                                }
                                if(s.charAt(0) == s1.charAt(s1.length()-1))
                                                return 1;
                                else
                                                return 0;
                }
}

Output

Find First Occurrence of character in a string

Write a program to find the first character occurrence in a string. Consider a string “Television” and we will find the occurrence of “i”.

Input and Output Format

  • Input consists of a string.
  • The output is a string saying the first occurrence of a character.

Refer sample output for formatting specifications

Sample Input 1:

Television

i

Sample Output 1:

First occurrence of i Found at 5

Program to find the first occurrence of a character in a string

Following are the steps to find the first occurrence of character:

  • Input a string from the user and a character whose first occurrence we have to find.
  • Call findFirstOccurenceOfChar() method.
  • Inside the method, declare and initialize i and count variables to 0.
  • Iterate over the string and compare the character at ith and the character to check. If both are the same then increment count variable and break from the loop.
  • If the count is not equal to 0 then print the first occurrence of the character position.
package com.company;

import java.util.Scanner;

public class Solution1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        char c = scanner.next().charAt(0);
        findFirstOccurenceOfChar(str,c);
    }

    private static void findFirstOccurenceOfChar(String str,char c) {
        int i =0;
        int count = 0;
        while(i < str.length()){
            if(str.charAt(i)==c){
                count++;
                break;
            }
            i++;
        }
        if(count==0){
            System.out.println("Not found");
        }
        else {
            System.out.println("First occurrence of "+c+" Found at "+i);
        }
    }
}

Output

Check String Contains Special characters

Write a program to validate if the string contains special characters or not. Consider a string “Hello@123”, this contains a special character so print “contains the special character”.

Input and Output Format

  • Input consists of a string.
  • The output is a string saying contains special characters or not.

Refer sample output for formatting specifications

Sample Input 1:

Hello@123

Sample Output 1:

contains special characters

Program to check string contains special characters using regex

Following are the steps to validate if the string contains any special character or not.

  • Input a string from the user.
  • Create a pattern using regex.
[^A-Za-z0-9]
    • [^A-za-z0-9] denotes a string made up of characters other than alphanumeric and blank spaces.
  • Match the pattern with the given input string.
  • If the match is found then print “contains special character” else print “does not contain the special character”.
package com.company;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Solution2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        Pattern p = Pattern.compile("[^A-Za-z0-9 ]");
        Matcher m = p.matcher(str);
        if(m.find()){
            System.out.println("contains special characters");
        }
        else {
            System.out.println("Does not contains special characters");
        }
    }
}

Output

Thus, in this way, we learned how to check characters in a string in Java.