简体   繁体   English

计算字符串中的大小写字符

[英]Counting upper and lower case characters in a string

First off, I know this is far from professional.首先,我知道这远非专业。 I'm trying to learn how to work with strings.我正在尝试学习如何使用字符串。 What this app is supposed to do is take a simple text input and do a few things with it:这个应用程序应该做的是接受一个简单的文本输入并用它做一些事情:

count letters, count upper and lower case letters, count words and count spaces.数字母,数大小写字母,数单词和数空格。 Here is what I've done:这是我所做的:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Case Check</title>
    <script type="text/javascript">
        function checkCase(text)
        {   

            var counter = 0;
            var letters = 0;
            var lowercase = 0;
            var uppercase = 0;
            var spaces = 0;
            var words = 0;


            for(; counter < text.length; counter++)
            {
                if(isUpperCase(text.charAt(counter))) {uppercase ++; letters++;}
                if(isLowerCase(text.charAt(counter))) {lowercase ++; letters++;} 
                if((text.charAt(counter) == " ") && (counter < text.length))
                {
                    spaces += 1;
                    words += 1;
                }
                if((text.charAt(counter) == ".") || (text.charAt(text(counter)) == ",")) continue;
            }
            return  [letters, lowercase, uppercase, spaces, words];
        }

        function isUpperCase(character)
        {
            if(character == character.toUpperCase) return true;
            else return false;
        }

        function isLowerCase(character)
        {
            if(character == character.toLowerCase) return true;
            else return false;
        }
    </script>
</head>
<body>
    <script type="text/javascript">
        var typed = prompt("Enter some words.");
        var result = checkCase(typed);
        document.write("Number of letters: " + result[0] + "br /");
        document.write("Number of lowercase letters: " + result[1] + "br /");
        document.write("Number of uppercase letters: " + result[2] + "br /");
        document.write("Number of spaces: " + result[3] + "br /");
        document.write("Number of words: " + result[4] + "br /");
    </script>
</body>

Made several changes due to users' suggestions.根据用户的建议进行了一些更改。 The problem now is that it won't let me treat 'text' like a string object.现在的问题是它不会让我将“文本”视为字符串对象。

Use regular expressions.使用正则表达式。

Example示例

var s = "thisIsAstring";
var numUpper = s.length - s.replace(/[A-Z]/g, '').length;  

// numUpper = 2

Se more at JavaScript replace/regex更多见JavaScript 替换/正则表达式

You can use match() and regular expressions.您可以使用 match() 和正则表达式。

var str = "aBcD"; 
var numUpper = (str.match(/[A-Z]/g) || []).length;    // 2

Not sure if whole problem, but bad paren on this one不确定是否是整个问题,但对这个问题不好

if(text.charAt(letters)) == " " && text(letters) < text.length)
                       ^

Should be应该是

if(text.charAt(letters) == " ") && text(letters) < text.length)
                              ^

And actually I'd make it事实上我会做到的

if((text.charAt(letters) == " ") && (text(letters) < text.length))

isUpperCase and isLowerCase are not JavaScript functions. isUpperCaseisLowerCase不是 JavaScript 函数。

You can replace them with something like你可以用类似的东西替换它们

var isUpperCase = function(letter) {
    return letter === letter.toUpperCase();
};

var isLowerCase = function(letter) {
    return letter === letter.toLowerCase();
};

There were a lot of syntax errors in your code which you need to check.您的代码中有很多语法错误需要检查。

I was also getting confused with all your brackets so instead of using the charAt I just referenced the string like an array.我也对你所有的括号感到困惑,所以我没有使用charAt而是像数组一样引用字符串。 So instead of text.charAt(letters) I used text[letters] which I found easier to read.因此,我使用text[letters]而不是text.charAt(letters) ,我发现它更容易阅读。

See the full jsFiddle here .这里查看完整的 jsFiddle。 I modified your code slightly because jsFiddle doesn't allow document.write我稍微修改了你的代码,因为 jsFiddle 不允许document.write

Another solution using CharCodeAt() method.另一种使用 CharCodeAt() 方法的解决方案。

const bigLettersCount = (str) => {
  let result = 0;
  for (let i = 0; i < str.length; i += 1) {
    if (str.charCodeAt(i) > 64 && str.charCodeAt(i) <91 ) {
      result += 1;
    }
   }
   return result
  }

console.log(bigLettersCount('Enter some words.'))

Another solution is using Array.from() make an array which includes each character of str and then using reduce() to count the number of the uppercase letters.另一种解决方案是使用Array.from()创建一个包含str每个字符的数组,然后使用reduce()来计算大写字母的数量。

 const str = 'HeLlO'; const res = Array.from(str).reduce((acc, char) => { return acc += char.toUpperCase() === char; }, 0); console.log(res);

Most of the solutions here will fail when string contains UTF8 or diacritic characters.当字符串包含 UTF8 或变音符号时,这里的大多数解决方案都会失败。 An improved version that works with all strings can be found at the turbocommons library, here:可以在 turbocommons 库中找到适用于所有字符串的改进版本,这里:

https://github.com/edertone/TurboCommons/blob/1e230446593b13a272b1d6a2903741598bb11bf2/TurboCommons-Php/src/main/php/utils/StringUtils.php#L391 https://github.com/edertone/TurboCommons/blob/1e230446593b13a272b1d6a2903741598bb11bf2/TurboCommons-Php/src/main/php/utils/StringUtils.php#L391

Example:示例:

// Returns 2
StringUtils.countByCase('1声A字43B45-_*[]', StringUtils.FORMAT_ALL_UPPER_CASE);

// Returns 1
StringUtils.countByCase('1声A字43B45a-_*[]', StringUtils.FORMAT_ALL_LOWER_CASE);

More info here:更多信息在这里:

https://turbocommons.org/en/blog/2019-10-15/count-capital-letters-in-string-javascript-typescript-php https://turbocommons.org/en/blog/2019-10-15/count-capital-letters-in-string-javascript-typescript-php

Play with it online here:在这里在线玩:

https://turbocommons.org/en/app/stringutils/count-capital-letters https://turbocommons.org/en/app/stringutils/count-capital-letters

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM