使用Java检查字符串中的邻居 [英] Check Neighbours in a String with Java
本文介绍了使用Java检查字符串中的邻居的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用字符串(如电话" ),我想知道字符 的邻居>'o'在这种情况下,我尝试使用String迭代器,但这给了我一个在使用charAt()之前或之后,我将超出-1或无限循环范围
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;
}
}
推荐答案
您可以尝试类似的方法.当然,您仍然可以对代码进行更改以获得预期的结果.
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?
这篇关于使用Java检查字符串中的邻居的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文