×

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

Highest precedence in Java

In Java, the operator is the first thing that springs to mind when discussing precedence. The order in which the operators in an expression are evaluated is controlled by a...

3 minutes read.

Dangling Else problem in Java

A language interpretation uncertainty is the hanging other issue. The following two types of condition executed code are both possible in programming: 1. if-then-else form 2. if-then form When dealing with the nested...

3 minutes read.

How to Convert Hexadecimal to Decimal in Java

How to Convert Hexadecimal to Decimal in Java There are two methods to convert Hexadecimal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method It is a static method of...

2 minutes read.

Java Session

Session indicates interval of time. A session is a simple  time interval in which servers and client interacts. To maintain the state of the client or user we use technologies...

5 minutes read.

Multiple Inheritance Programs in Java

A component of the object-oriented notion known as multiple inheritances allows a class to inherit properties from multiple parent classes. When methods that have the same signature are present in...

4 minutes read.

Java Math negateExact() Method

The negateExact() method of Math class returns the negation for the specified argument, throwing an exception if the result overflows an int or a long. Syntax: public static int negateExact (int a)public...

1 minute read.

Java Logo

Java is a prominent and extensively used object-oriented programming language. In 1995, Sun Microsystems created it. Later in 2009, Oracle Corp takeover Java. History of Java Logo The name of the island...

3 minutes read.

Fibonacci Series Program in Java

Fibonacci Series Program in Java using Recursion Fibonacci series is a series whose every term is comprised of adding its previous two terms, barring the first two terms 0 and 1....

3 minutes read.

Java Open File

Java Desktop class give an open() strategy to open a filr. It has a place with a java.awt package. Work area execution is stage subordinate, so it is important to...

5 minutes read.

How to compare dates in Java

Introduction: In Java, dates can be compared using a similar interface's compareTo() technique. This method returns 'zero' if each date is the same, returns a rate "more than 0" if...

6 minutes read.

Differences between Lock and Monitor in Java Concurrency

In this tutorial, we will discuss the overview of Lock and Monitor and the differences between them. Introduction Java Concurrency is the ability to perform specific tasks at a time parallelly. The...

4 minutes read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log...

7 minutes read.

Inheritance Program in Java

Inheritance Program in Java Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help...

7 minutes read.

Bedrock vs Java

The popularity of Minecraft, a sandbox video game, has skyrocketed. The scope, level of complexity, and variety of gameplay in this game are enormous, and user-generated content has helped to...

4 minutes read.

Java Stringjoiner Class

StringJoiner is a class which is used to construct a sequence of characters which are separated by a delimiter. Optionally, it starts with a provided prefix and ended with the...

5 minutes read.

Java Integer shortValue() method

The shortValue() method of Java Integer class returns a short value for this Integer after a narrowing primitive conversion. Syntax public short shortValue () Parameters NA Overrrides: The shortValue () overrides : shortValue in class Number  Return Value This...

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.

Adapter class in Java

By using the adapter classes, we can implement Listener interfaces. With the help of adapter classes, we can save code as it provides all implementation methods of listener interfaces Advantages of...

3 minutes read.

Java Double Keyword

In java primitive data types, we have two different types of data types which are Boolean and floating-point data types.In floating data type again we have four types which are...

3 minutes read.