×

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified character in the string. We will use the Java programming language to execute program. Additionally, you can also use other programming language by following same logic to get output.

Approach

The main logic to the given problem is you need to traverse the string by comparing each character of the string with the required character. If you find the required character, you need to output the message saying whether the character is present in the string or not.

Example

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


public class Main
{
public static void main (String [] args) {

Scanner sc = new Scanner (System.in);
int found = 0; 
               // found is used to give the output the index of required character in the string
System.out.println(" enter the String");
String s = sc.next ();
                   // string input will be given by the user
System.out.println("enter the character to find from the string ");
char c=sc. next () .charAt (0);
                   // character input will be given by the user
for (int i = 0; i < s.length (); i++)
{ 
    if (c == s.charAt (i))
                          // traversing the string and comparing it with the required character
    {
        found = i; 
       // if the character is found then found will be updated to i and will exit the loop         break;
    }
    
}

if (found!=0)
{
    System.out.print ("character is present in the string at the index = " +found); 
                            // output message
    
}
else
{
    System.out.print ("character is not present in the string");
                        // output message
    
}
}
}

Output

Program To Check Whether A Given Character Is Present In A String Or Not
Program To Check Whether A Given Character Is Present In A String Or Not

Find the position of a given character in the string

The given problem statement is that you will be given a string. You will have to find the position of the character presented in the given string. We will use the Java programming language to execute program. Additionally, you can also use other programming language by following same logic to get output.

Approach

The main logic to the given problem is you need to traverse the string by comparing each character of the string with the required character. If you find the character, then you need to output the index of that character in the string.

Example

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


public class Main
{
public static void main (String [] args) {

Scanner sc = new Scanner (System.in);
int found = 0; 
               // found is used to give the output the index of required character in the string
System.out.println(" enter the String");
String s = sc.next ();
                   // string input will be given by the user
System.out.println("enter the character to find from the string ");
char c=sc. next () .charAt (0);
                   // character input will be given by the user
for (int i = 0; i < s.length (); i++)
{ 
    if (c == s.charAt (i))
                          // traversing the string and comparing it with the required character
    {
        found = i; 
       // if the character is found then found will be updated to i and will exit the loop         break;
    }
    
}

if (found!=0)
{
    System.out.print ("character is present in the string at the index = " +found); 
                            // output message
    
}
else
{
    System.out.print ("character is not present in the string");
                        // output message
    
}
      }
}
Program To Check Whether A Given Character Is Present In A String Or Not

Suppose the required character from the string is repeated. Then the index of the first occurrence will be printed on the screen.


Related Topics

Volatile keyword in Java

Multiple threads can change a variable's value by using the volatile keyword. Making classes thread-safe is another application for it. It indicates that using a method or an instance of...

3 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Difference between String, StringBuffer and StringBuilder in java

What is a string in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java Integer divideUnsigned() method

The divideUnsigned() method of Integer class returns the unsigned quotient by dividing the first argument by the second argument. Syntax public static int divideUnsigned (int dividend , int divisor) Parameters The parameter ‘dividend’ represents...

1 minute read.

Sort Elements by Frequency in Java

To sort the elements in Java by using frequency, we need an input array. We should create a function that sorts the elements in an array by using their frequencies...

3 minutes read.

Java String charAt() method

It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1. Syntax: public char charAt (int index) Parmeters It accepts only...

3 minutes read.

Difference between next() and nextline() in Java

One of the simplest methods for receiving input of the basic data types, also including int, double, and strings, in Java, is to use the Scanner class, which is part...

3 minutes read.

Java 8 Multimap

Java comes with several practical built-in collection libraries. However, there are situations when we need specialized collections that are not included in the Java standard library. The Multimap is one...

7 minutes read.

Dining Philosophers problem in Java

The Problem of the Dining Philosophers illustrates a concurrency issue involving the distribution of scarce resources among conflicting processes. Problem Statement Imagine a dining table with a circle in the middle and five...

3 minutes read.

Isomorphic String in Java

In this tutorial, we will understand what is meant by isomorphic String in java. We will also see a Java program to find out if the string is isomorphic or...

4 minutes read.

Java String toLowerCase() methods

Java String toLowerCase() method is used to convert all the characters of the String into lower case. Syntax: public String toLowerCase()              public String toLowerCase(Locale locale) Returns: It returns Lower...

1 minute read.

Collection Programs in Java

Collection Programs in Java Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly...

4 minutes read.

Java Integer reverse() method

The reverse() method of Java Integer class returns the value obtained by reversing the order of the bits in the 2’s complement binary representation. Syntax public static int reverse (int i)  Parameters The parameter...

1 minute read.

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.

How to add Elements in Array in Java

Consider an array of the size n, in the given size we must add the elements in the given array. In this tutorial we are preferred to learn how to add...

3 minutes read.

Type Annotations in Java

Only declarations were eligible for annotations in earlier versions of Java. With Java 8, you may now annotate any type use, including types in declarations, generics, and casts: @Encrypted String data; List<@NonNull...

6 minutes read.

Java File Extension

A computer file's suffix is called its file extension. It is easily recognized since it appears immediately after a period (.) in the file name. Consider the file Demo.java as an...

3 minutes read.

Fibodiv Number in Java

Before understanding the concept of the fibodiv number, one should realize what the Fibonacci number is. What are Fibonacci Numbers? The Fibonacci sequence of whole numbers is composed of the numbers 0,...

5 minutes read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

Java String Matches vs Contains

String Matches in Java The matches() function and its variations are used to determine whether or not a provided text matches a regular expression. The functioning as well as output of...

3 minutes read.