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

时间:2015-03-18 16:47:08

标签: java string integer

这计算了字符串的整个长度,例如我是一个男人= 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);
    }

}

5 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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);
                }
    }

答案 3 :(得分:0)

让我知道这是否有助于你!!

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());
}
}

答案 4 :(得分:-1)

这也可能是一个解决方案(替换功能)...

String input = sc.nextLine();    

System.out.println(input);

String inputWithoutSpace = input.replace(" ", "")  

int length = inputWithoutSpace.length();    
System.out.println(length);