问题
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;
}
}
回答1:
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?
回答2:
s.charAt(i--)
subtracts one in loop. It it leads to endless loop. You can try s.charAt(i-1)
instead
回答3:
try this :
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;
}
this will get the next and previous character off specific char and put them inside array of 2 character.
来源:https://stackoverflow.com/questions/65431509/check-neighbours-in-a-string-with-java