javaloopscharactercharat

Check Neighbours in a String with Java


in a string like "phone" i want to know the neighbour of the character 'o' in this case 'h' and 'n' i tryed with a String Iterator but that gives me either before or after and with charAt() i will be out of range by -1 or endless loop

String s = textArea.getText();
    
    for( int i = 0; i < s.length(); i++) {
        char ch = s.charAt(i);
        char tz = s.charAt(i--);
                            
            System.out.print(ch);
            if(ch == 'n') {
            System.out.print(tz);
            break;
            }
        }

Solution

  • you could try something like this. Of course, you can still do changes to the code to get the expected result.

    public void stringSplit(String text)
        {
            char[] letters = text.toCharArray();
            for (int i=0; i<letters.length;i++)
            {
                if (i!=0 && i!=letters.length-1){
                    System.out.print("neighbour left: " + letters[i - 1] +'\n');
                    System.out.print("actual: " + letters[i]+'\n');
                    if (letters[i - 1] == 'n') { //here I used the condition from your code
                        System.out.print("neighbour right: " + letters[i + 1] +'\n');
                        break;
                    }
                }
                else if(i==0)
                {
                    System.out.print("actual: " + letters[i]+'\n');
                    System.out.print("neighbour right: " + letters[i + 1] +'\n');
                }
                else{
                    System.out.print("neighbour left: " + letters[i - 1] +'\n');
                    System.out.print("actual: " + letters[i]+'\n');
    
                    System.out.println("end of string");
                }
            }
        }
    

    In this version you have all the corner cases checked. Do you still have questions?