Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

finding out if a character is present in a string

Status
Not open for further replies.

laina222

Technical User
Sep 7, 2001
172
US
Hi all!
I'm currently trying to write a program that takes a character from a user and determines if that character is present within a string. For example, let's say theuser enters the letter 'r' and I want the system to determine how many times the character 'r' is present in the phrase "Chocolate is good for you.", so the system would return '1' since 'r' is only in that phrase once.
Your help is appreciated!
Laina
 
Try this
Code:
public class test {
  public static void main(String[] args) {
    String input = "o";
    System.out.println("Enter a letter");
    InputStreamReader ir = new InputStreamReader(System.in);
    try{
      BufferedReader br = new BufferedReader(ir);
      input = br.readLine();
    }catch(Exception e){}
    String temp = "Chocolate is good for you";
    int x = 0;
    int ctr = 0;
    boolean repeat = true;
    while(repeat == true)
    {
      x = temp.indexOf(input, x + 1);
      if (x == -1)
        repeat = false;
      else
        ++ctr;
     }
     if(x == -1 && ctr == 0)
       System.out.println("The letter " + input + " was not found");
     else
       System.out.println("The letter " + input + " was found " + ctr + " times");
  }
}
 
im sure strstr does this for you!

use strstr to find the first occurance of a string within another, then use strstr on the rest of the string etc until strstr returns null!

the point of java is that you dont have to do all the C++ shit!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top