Q:

Java finding a particular letter for the first time

I am developing a program in Java. I need to find a particular text inside a string. Suppose string is 'Hawaiie'. My need is to search for 'd' & 'e'. If 'e' comes first 'e' has to be returned and if 'd' comes first then 'd' has to be returned. In string 'Hawaiie' since 'e' is the first letter 'e' has to be returned. I tried the following code for that but it is returning only the position of letter, not the letter itself.
String str1 = new String("Hawaiee");
System.out.println(str1.indexOf('e');

A:

Try this: here, if none of the characters are there: it will return 'o', you can put any default character for comparison.
  public char getFirstChar(String str) {

    int indexOfd = str.indexOf('d');
    int indexOfe = str.indexOf('e');
    if (str.indexOf('d') != -1) {
        if (str.indexOf('e') != -1) {
            if (indexOfd < indexOfe) {
                return 'd';
            } else {
                return 'e';
            }
        } else {
            return 'd';
        }

    } else {
        if (str.indexOf('e') != -1) {
                return 'e';
        } else {
            return 'o';
        }

    }
}

A:

Seems like you need to get the index of each character (d & e) and compare the indexes. Then return the appropriate character depending on which index is less (don't forget to exclude -1 since that means it wasn't found).

A:

public char getFirstChar(String s, char a, char b){
    for (int i = 0; i < s.length(); i++){
        char c = s.charAt(i);

        if (c == a){
            return a;
        }
        if (c == b){
            return b;
        }
    }
    return ' ';
}

