settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Value of a String - String Task

+5 votes

Write a program which finds the sum of the ASCII codes of the letters in a given string.  Your tasks will be a bit harder, because you will have to find the sum of either the lowercase or the uppercase letters.

On the first line, you will receive the string.

On the second line, you will receive one of two possible inputs:

  • If you receive “UPPERCASE” find the sum of all uppercase English letters in the previously received string
  • If you receive “LOWERCASE” find the sum of all lowercase English letters in the previously received string

You should not sum the ASCII codes of any characters, which is not letters.

At the end print the sum in the following format:

  • The total sum is: {sum}

Examples:

value of a string string task

asked in PHP category by user hues

1 Answer

+4 votes

Here is my solution:

<?php

$word = readline();
$case = readline();
$sum = 0;

for ($i = 0; $i < strlen($word); $i++) {
    if ($case === "LOWERCASE") {
        if (ctype_lower($word[$i]) && ctype_alnum($word[$i])) {
            $sum += ord($word[$i]);
        }
    } else if (ctype_upper($word[$i]) && ctype_alnum($word[$i])) {
        $sum += ord($word[$i]);
    }
}

echo "The total sum is: " . $sum;
answered by user andrew
...