Java 程序计算字符串中的总字符数

编写一个Java程序,通过示例计算字符串中的总字符数。我们可以使用内置的length函数来获取字符串的长度。但是,我们使用循环来获取字符串字符的总数。

在此Java示例中,我们使用for循环从头到尾迭代字符串。在循环中,我们使用if语句来检查字符是否不为空。如果为真,则计数将从0递增到1。

import java.util.Scanner;

public class CharactersInAString {
	private static Scanner sc;
	public static void main(String[] args) {
		String charsinstr;
		int count = 0;
		
		sc= new Scanner(System.in);

		System.out.print("\nPlease Enter a String to Count Characters =  ");
		charsinstr = sc.nextLine();
		
		for(int i = 0; i < charsinstr.length(); i++)
		{
			if(charsinstr.charAt(i) != ' ') {
				count++;
			}
		}		
		System.out.println("\nThe Total Number of Characters  =  " + count);
	}
}
Java Program to Count Total Characters in a String using for loop

使用while循环计算字符串中总字符数的Java程序

import java.util.Scanner;

public class CharactersInAString1 {
	private static Scanner sc;
	public static void main(String[] args) {
		String charsinstr;
		int count = 0, i = 0;
		
		sc= new Scanner(System.in);

		System.out.print("\nPlease Enter a String to Count Characters =  ");
		charsinstr = sc.nextLine();
		
		while(i < charsinstr.length())
		{
			if(charsinstr.charAt(i) != ' ') {
				count++;
			}
			i++;
		}		
		System.out.println("\nThe Total Number of Characters  =  " + count);
	}
}
Please Enter a String to Count Characters =  hello world

The Total Number of Characters  =  10

下面的程序使用函数计算字符串中的总字符数。在这里,我们在“计算字符串字符总数”示例中将逻辑分成了函数。

import java.util.Scanner;

public class CharactersInAString2 {
	private static Scanner sc;
	public static void main(String[] args) {
		String charsinstr;
		
		sc= new Scanner(System.in);

		System.out.print("\nPlease Enter a String to Count Characters =  ");
		charsinstr = sc.nextLine();
		
		int count = TotalNumberofCharacters(charsinstr);
		
		System.out.println("\nThe Total Number of Characters  =  " + count);		
	}
	public static int TotalNumberofCharacters(String charsinstr) {
		int i, count = 0;
		
		for(i = 0; i < charsinstr.length(); i++)
		{
			if(charsinstr.charAt(i) != ' ') {
				count++;
			}
		}		
		return count;
	}	
}

Please Enter a String to Count Characters =  info tutorial

The Total Number of Characters  =  12