Search for character positions in a string

How to find a character in a String and print the character position along the entire string? For example, I want to find the position of 'o' in this line: "you are awesome honey" and get the answer = 1 12 17 .

I wrote this, but it does not work:

 public class Pos { public static void main(String args[]){ String string = ("You are awesome honey"); for (int i = 0 ; i<string.length() ; i++) if (string.charAt(i) == 'o') System.out.println(string.indexOf(i)); } } 
+8
java string character
source share
5 answers

You were almost right. The problem is your last line. You should type i instead of string.indexOf(i) :

 public class Pos{ public static void main(String args[]){ String string = ("You are awesome honey"); for (int i = 0 ; i<string.length() ; i++) if (string.charAt(i) == 'o') System.out.println(i); } } 
+3
source share

Start with the first character and repeat all the characters to the end. At each step, check to see if the character is an "o". If he then prints the position.

0
source share
  static ArrayList<String> getCharPosition(String str, char mychar) { ArrayList<String> positions = new ArrayList<String>(); if (str.length() == 0) return null; for (int i = 0; i < str.length(); i ++) { if (str.charAt(i) == mychar) { positions.add(String.valueOf(i)); } } return positions; } String string = ("You are awesome honey"); ArrayList<String> result = getCharPosition(string, 'o'); for (int i = 0; i < result.size(); i ++) { System.out.println("char position is: " + result.get(i)); } 

Output:

 char position is: 1 char position is: 12 char position is: 17 
0
source share

Here in Java:

  String s = "you are awesome honey"; char[] array = s.toCharArray(); for(int i = 0; i < array.length; i++){ if(array[i] == 'o'){ System.out.println(i); } } 
0
source share

Here is a function to find all the positions of a specific character in a string

 public ArrayList<Integer> findPositions(String string, char character) { ArrayList<Integer> positions = new ArrayList<>(); for (int i = 0; i < string.length(); i++){ if (string.charAt(i) == character) { positions.add(i); } } return positions; } 

And use it

 ArrayList<Integer> result = findPositions("You are awesome honey",'o'); // result will contains 1,12,17 
0
source share

All Articles