java - Java 包围字符方法

标签 java arrays list loops foreach

我正在开发一种java方法,用于检查字符数组中的字符是否被字符包围。例如:abcdc,d 被 c 包围。例如:abccc,周围没有字母。这是我到目前为止所拥有的。

public static boolean surroundedCharacter(char[] letters){
    boolean result = false;
    for(char letter : letters)
        if(letters[letter-1] == letters[letter+1]){
            result = true;
        }
    return result;
} }

所以我基本上有一个 for every 循环遍历字母中的字母,并检查该位置之前的字母是否等于该位置之后的字母。如果是,则意味着该字母被包围,并且应将结果更改为 true。 junit测试说if语句是错误的,但我不知道如何修复它。任何帮助表示赞赏。

最佳答案

您必须使用整数作为索引:

public static boolean surroundedCharacter(char[] letters){
    boolean result = false;
    for(int i = 1; i < letters.length - 1; i++) {
        // You said that if the string is "abccc", should return false.
        // So, we check if the previous or the next letter is different to 
        //the actual value of i
        if((letters[i-1] == letters[i+1]) && (letters[i-1] != letters[i])) {
            result = true;
        }
    }
    return result; 
}

关于java - Java 包围字符方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42890213/

相关文章:

python - 包含特殊字符的列表

java - 创建 pdf 的保存对话框

java - 使用流创建 xml,缺少编码属性

java - 如何使用定时器

c++ - 在此初始化方法中将整个数组设置为 NULL 是 C++ 标准吗?

PHP调用Python,返回多个值

java - 为什么命名字符串变量 String 是一个有效的 Java 结构?

javascript - 使用递归输出所有嵌套数组元素

c# - 在隔离存储中存储对象列表的问题

python - 通过迭代创建列表的最快方法