Write A Script To Calculate The Length Of A String And Count The Number Of Words In The Given String Without Using String Functions.

0

Write a script to calculate the length of a string and count the number of words in the given string without using string functions.

Write a script to calculate the length of a string and count the number of words in the given string without using string functions.

Here is a PHP script for Calculate Length Of A String:


PROGRAM
<?php

function calculateStringLength($string) {
    $length = 0;
    $characters = str_split($string);

    foreach ($characters as $character) {
        $length++;
    }

    return $length;
}

function countWords($string) {
    $wordCount = 0;
    $words = explode(' ', $string);

    foreach ($words as $word) {
        if (!empty(trim($word))) {
            $wordCount++;
        }
    }

    return $wordCount;
}

$string = "Diploma Computer Engineering";
$length = calculateStringLength($string);
$wordCount = countWords($string);

echo "String length: " . $length . "<br>";
echo "Word count: " . $wordCount . "<br>";

?>

OUTPUT
String length: 28
Word count: 3

Explanation

  • In this script, the calculateStringLength function takes a string as input and calculates its length by converting it into an array of characters and then iterating over each character. The length is incremented for each character, resulting in the total length of the string.
  • The countWords function counts the number of words in a given string by using the explode function to split the string into an array of words based on spaces. It then iterates over each word, trims any leading or trailing spaces, and increments the count if the word is not empty.
  • Finally, the script demonstrates an example usage by calculating the length and word count of a sample string and displaying the results.


❤️ I Hope This Helps You Understand, Click Here To Do More Exercise In PHP Programming.

Post a Comment

0Comments
Post a Comment (0)