Java教程

Java对字符串中的字符总数进行计数

在此程序中,我们需要计算字符串中存在的字符数: The best of both worlds
要计算字符串中存在的字符数,我们将遍历字符串并计算字符数。在上面的示例中,字符串中存在的字符总数为19。
要进行编程,请遵循以下算法:

算法

步骤1: START 步骤2: DEFINE字符串string ="The best of both worlds"。 步骤3: SET count = 0。 步骤4: SET i = 0。直到 i < string.length 重复步骤5至步骤6 步骤5: 如果是 IF(string.charAt(i)!=''),然后 count= count +1。 步骤6: i = i + 1 步骤7: 打印计数。 步骤8: END

程序:

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);
    }
}
输出:
Total number of characters in a string: 19
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4