Java how to find a specific character in a string using array

Java how to find a specific character in a string using array

To find a specific character in a string using an array in Java, you can use the charAt() method of the String class to retrieve each character in the string and compare it to the desired character.

Here's an example of how to find a specific character in a string using an array in Java:

String string = "Hello, world!";
char target = 'o';

char[] chars = string.toCharArray();

for (int i = 0; i < chars.length; i++) {
  if (chars[i] == target) {
    System.out.println("Found character at index " + i);
  }
}
Sour‮:ec‬www.lautturi.com

In the above example, the toCharArray() method is used to convert the string to an array of characters. A loop is then used to iterate over the elements of the array and compare each character to the target character. If a match is found, the index of the character is printed to the console.

Alternatively, you can use the indexOf() method of the String class to find the index of the first occurrence of the desired character in the string. For example:

String string = "Hello, world!";
char target = 'o';

int index = string.indexOf(target);

if (index != -1) {
  System.out.println("Found character at index " + index);
} else {
  System.out.println("Character not found");
}

In the above example, the indexOf() method returns the index of the first occurrence of the target character in the string. If the character is not found, the method returns -1.

Created Time:2017-11-03 22:21:06  Author:lautturi