[英]how to calculate the length of a string without spaces in java
這將計算字符串的總長度,例如我是一個人= 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);
}
}
您可以嘗試用零字符替換所有空格:
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);
}
}
如果這對您有幫助,請告訴我!!
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);
}
}
這也可能是一個解決方案(替換功能)......
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.