简体   繁体   English

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

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

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

}

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());
int characters = 0;
for (int i = 0, length = string.length(); i < length; i++) {
  if (str.charAt(i) != ' ') {
    characters++;
  }
}
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);
                }
    }

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());
}
}
class NewClass 
 {
  public static void main(String args[])
   {
  String str ="how are you ";
  int count =0;
  for(int i=0;i<str.length();i++)
  {
   if(str.charAt(i)!= ' ')
  {

 count++;
 }
 }
 System.out.println(count);
 }
 }

this could also be a solution (replace-function) ...这也可能是一个解决方案(替换功能)......

String input = sc.nextLine();    

System.out.println(input);

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM