C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Program to count the total number of characters in a string
ExplanationIn this program, we need to count the number of characters present in the string. The best of both worlds To count the number of characters present in the string, we will iterate through the string and count the characters. In above example, total number of characters present in the string are 19. Algorithm
SolutionPython
string = "The best of both worlds";
count = 0;
#Counts each character except space
for i in range(0, len(string)):
if(string[i] != ' '):
count = count + 1;
#Displays the total number of characters present in the given string
print("Total number of characters in a string: " + str(count));
Output: Total number of characters in a string: 19 C
#include <stdio.h>
#include <string.h>
int main()
{
char string[] = "The best of both worlds";
int count = 0;
//Counts each character except space
for(int i = 0; i < strlen(string); i++) {
if(string[i] != ' ')
count++;
}
//Displays the total number of characters present in the given string
printf("Total number of characters in a string: %d", count);
return 0;
}
Output: Total number of characters in a string: 19 JAVA
public class CountCharacter
{
public static void main(String[] args) {
String string = "The best of both worlds";
int count = 0;
//Counts each character except space
for(int i = 0; i < string.length(); i++) {
if(string.charAt(i) != ' ')
count++;
}
//Displays the total number of characters present in the given string
System.out.println("Total number of characters in a string: " + count);
}
}
Output: Total number of characters in a string: 19 C#
using System;
public class CountCharacter
{
public static void Main()
{
String string1 = "The best of both worlds";
int count = 0;
//Counts each character except space
for(int i = 0; i < string1.Length; i++) {
if(string1[i] != ' ')
count++;
}
//Displays the total number of characters present in the given string
Console.WriteLine("Total number of characters in a string: " + count);
}
}
Output: Total number of characters in a string: 19 PHP
<!DOCTYPE html>
<html>
<body>
<?php
$string = "The best of both worlds";
$count = 0;
//Counts each character except space
for($i = 0; $i < strlen($string); $i++) {
if($string[$i] != ' ')
$count++;
}
//Displays the total number of characters present in the given string
print("Total number of characters in a string: " . $count);
?>
</body>
</html>
Output: Total number of characters in a string: 19
Next Topic#
|