用java检查字符串中的邻居

bq3bfh9z  于 2021-06-29  发布在  Java
关注(0)|答案(3)|浏览(321)

在像“phone”这样的字符串中,我想知道字符“o”的邻居,在这个例子中是“h”和“n”,我尝试了一个字符串迭代器,但是这给了我在charat()之前或之后的结果,我将超出-1的范围,或者是无限循环

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;
            }
        }
zd287kbt

zd287kbt1#

s.charAt(i--) 在循环中减去一。它会导致无尽的循环。你可以试试 s.charAt(i-1) 相反

yzckvree

yzckvree2#

试试这个:

public static void main(String[] args) {
    String s = "phone";
    char[] arr = neighbour(s, 'o');
    System.out.println("previous : "+arr[0]);
    System.out.println("next : "+arr[1]);
}

public static char[] neighbour(String s , char c){
    int index = s.indexOf(c);
    if(index == -1) throw new Error("character '"+c+"' not exist in \""+s+"\" ");
    char[] arr = new char[2];
    if(index > 0)
        arr[0] = s.charAt(index-1);
    if(index+1 < s.length())
        arr[1] = s.charAt(index+1);
    return arr;
}

这将使下一个和上一个字符脱离特定字符,并将它们放入2个字符的数组中。

0lvr5msh

0lvr5msh3#

你可以试试这样的。当然,您仍然可以对代码进行更改以获得预期的结果。

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");
            }
        }
    }

在这个版本中,你已经检查了所有的角落案例。你还有问题吗?

相关问题