程序检查字符串中的大写字母

program checking string of characters for capital letters

本文关键字:大写字母 字符串 检查 程序      更新时间:2023-09-26

好的,我有一个函数,它检查字母是否为大写,并返回'true'或'false'值。

function isUpperCase(aCharacter) {
    return (aCharacter >= 'A') && (aCharacter <= 'Z');
}

现在我希望它检查一个字符串,例如"AdfdfZklfksPaabcWsgdf",在程序遇到大写字母后,它将对这个字母之后的所有小写字母执行函数decryptWord,直到下一个大写字母为止,以此类推;(

function decryptMessage(cipherText, indexCharacter, plainAlphabet, cipherAlphabet) {
    for (var count = 0, count < cipherText.length; count++) {
        if (isUpperCase(cipherText.charAt(count))) {
            decryptWord(cipherText, indexCharacter, plainAlphabet, cipherAlphabet)
        } else {
            //i dont know what to do next
        }
    }
}

你能告诉我我的方向是否正确吗?

您是否考虑过在每个大写字符之前进行拆分的regex?例如

"AdfdfZklfksPaabcWsgdf".split(/(?=[A-Z])/);

结果:

["Adfdf", "Zklfks", "Paabc", "Wsgdf"]

通过这种方式,您可以一次管理一个"单词";每个字符的第一个字符总是大写,其余的都是小写。

isUpperCase函数为空格字符返回false,因此代码对空格字符和小写字符一视同仁。这可能就是为什么它对多个单词而不是单个单词感到恶心的原因。

与其处理大写和小写字母,为什么不将split作为非单词字符的输入呢?类似这样的东西:

var words = cipherText.split(/'W/), // 'W means non-word characters
    numWords = words.length;
for (var i = 0; i < numWords; i++) {
    decryptWord(words[i]);
}

我建议在decryptMessage函数中使用两个变量。第一个变量last_caps将存储前一个大写字母的索引。第二个变量是count,它的工作方式与现有的非常相似。这可以让您知道上一个大写字母在哪里,所以当您找到下一个大写时,您可以在它们之间的小写字母上使用decryptWord

for循环的迭代

  • 如果索引count处的字符为大写,则:
    • 如果count - last_caps > 1,则:
      • 使用decryptWord对从last_caps开始到count结束的子字符串进行解密。根据需要操作值以包括/排除大写字母
    • count覆盖last_caps。(last_caps = count
  • for迭代结束

在大写字母上拆分的JavaScript函数:

String.prototype.splitForCapitalLetters = function () {
    var string = this;
    if (string.length) {
        string = string.split(/(?=[A-Z])/);
    }
    return string;
};

呼叫:

"AnyString".splitForCapitalLetters();

结果:

["Any", "String"]

列是字符串数组,并保留完全大小写,如大写或小写

function cipherText(columns) {
    for (var i = 0; i < columns.length; i++) {
        if (!isAnyCase(columns[i])) {
            columns[i] = columns[i].split(/(?=[A-Z])/).join(" ");
        }
    }
    return columns;
}
function isAnyCase(text) {
    return (text == text.toUpperCase() || text == text.toLowerCase());
}

调用函数

var columns = cipherText(arr);