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

hc2pp10m  于 2023-01-19  发布在  Java
关注(0)|答案(6)|浏览(137)

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

}
umuewwlo

umuewwlo1#

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

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

hkmswyz62#

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

s4n0splo3#

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

uqcuzwp84#

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

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

hpcdzsge5#

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

String input = sc.nextLine();    

System.out.println(input);

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

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

xe55xuns6#

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

相关问题