java java中如何计算没有空格的字符串的长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29127884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:43:39  来源:igfitidea点击:

how to calculate the length of a string without spaces in java

javastringinteger

提问by Big Moe Pasha

this calculate the whole length of the string eg i am a man= 7 letter and 9 characters i just want the amount of the total letters

这计算了字符串的整个长度,例如我是一个人 = 7 个字母和 9 个字符我只想要总字母的数量

import java.util.Scanner;
public class AssignmentProgramming {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);

        System.out.println("Please enter a string");

        String input = sc.nextLine();

        System.out.println(input);

        String str = input;
        String[] myString = str.split(" ");
        int length = str.length();
        System.out.println(length);
    }

}

回答by Luiggi Mendoza

You could try replacing all empty spaces by zero char:

您可以尝试用零字符替换所有空格:

String test = "Hello world    1 2 3 4 5";
System.out.println(test.replace(" ", "").length());

回答by bvaughn

int characters = 0;
for (int i = 0, length = string.length(); i < length; i++) {
  if (str.charAt(i) != ' ') {
    characters++;
  }
}

回答by Sonaj Gupta

import java.util.*;

class cont

    {
        public static void main(String arg[]){
        int sum=0;
        Scanner s=new Scanner(System.in);
        System.out.println("please enter string");
        String val=s.nextLine();
        int len=val.length();
            for(int i=0;i<len;i++){
                if(val.charAt(i)==' ')
                    {
                        continue;
                    }
                    sum++;
                    }
                    System.out.println(sum);
                }
    }

回答by Maravilloso'AK

Let me know if this helps you out !!

如果这对您有帮助,请告诉我!!

import java.util.*;
public class CountCharacters 
{
public static void main(String[] args) 
{
System.out.println("Entered a string ");
Scanner sc= new Scanner(System.in);
String originalString=sc.nextLine();
System.out.println("Entered string is "+originalString);
String newString=originalString.replaceAll(" ", "");
System.out.println("New string after removing spaces is "+newString);
System.out.println("Number of characters in string are "+newString.length());
}
}