2013-02-19 4 views
4

이것은 내 간단한 코드입니다.문자열 내에서 공백이 아닌 문자 수 읽기

import java.util.Scanner;

public class WordLines 
{ 
    public static void main(String[] args) 
    { 
     Scanner myScan = new Scanner(System.in); 
     String s; 

     System.out.println("Enter text from keyboard"); 

     s = myScan.nextLine(); 

     System.out.println("Here is what you entered: "); 
     System.out.println(s.replace(" ", "\n")); 
    } 
} 

"굿모닝 월드!"와 같은 문장을 입력하는 경우 (이 줄에 17 개의 공백이 아닌 문자가 있음)

텍스트를 표시 할 수 있고 그 위에 공백이 아닌 문자의 수를 인쇄 할 수 있습니까?

다시 모든 도움

덕분에 해결!

System.out.println(s); 
System.out.println(s.replace(" ", "").length()); 
+0

그냥 내 솔루션 :보다 구체적인 봤는데해야 죄송합니다 –

답변

2

이 시도

public static int countNotBlank(String s) { 
    int count = 0; 
    for(char c : s.toCharArray()) { 
     count += c == ' ' ? 0 : 1; 
    } 
    return count; 
} 
+0

일에 대처하는 또 다른 방법을보고 내 게시물 봐. 어떻게 만들 수 있습니까? 내 텍스트 문자열을 인쇄 한 다음 텍스트 내에 공백이 아닌 문자의 양을 나열하십시오. –

+0

보다 더 문제 – user2086204

+0

업데이트 됨. 그러나 "비어 있지 않은 문자의 양을 나열하십시오"는 실제로 의미가 없습니다. :) – cowls

0

같은 것을 수행합니다 :

4

사용하는 모든 공백 (공백, 줄 바꿈, 탭)을 삭제하는 정규 표현식을 다음 단순히 문자열 길이를 취할.

input.replaceAll("\\s+", "").length() 
+0

+1 최상의 해결책 –

0

당신은 다음과 같이 문자열에서 비 공백 문자를 계산할 수 있습니다 : 유에서 사용자 CTRL + C 필요

import java.util.Scanner; 

public class WordLines { 

    public static void main(String[] args) { 

     Scanner myScan = new Scanner(System.in); 
     String s; 

     System.out.println("Enter text from keyboard"); 

     s = myScan.nextLine(); 

     String[] splitter = s.split(" "); 

     int counter = 0; 
     for(String string : splitter) { 
      counter += string.length(); 
     } 

     System.out.println("Here is what you entered: "); 
     System.out.println(counter); 

    } 

} 
+0

이것은 완벽하게 작동했습니다! 고맙습니다! – user2086204

+0

@ user2086204 도움이 되니 기쁩니다. 대답이 도움이된다면 답안을 upvote 할 수 있고 표시는 받아 들일 수 있습니다. –

0

그것을 처리하는 또 다른 방법 마지막으로 입력을 끝내고 싶을 때.

0
import java.util.Scanner; 


public class WordLines 
{ 

    public static void main(String[] args) { 

    Scanner myScan = new Scanner(System.in); 
    String s=""; 

    System.out.println("Enter text from keyboard"); 
    while(myScan.hasNextLine()) s = s+myScan.nextLine(); 

    System.out.println("Here is what you entered: "); 
    System.out.println(s.replace(" ", "\n")); 

    } 

} 

int non_blank_counter = 0; 
//your code to read String 
for(int i=0;i<s.length();i++){ 
// .. inside a loop ..// 
if (myStr.charAt(i) != ' ') 
    non_blank_counter++; 
} 
System.out.println("number of non blank characters are "+non_blank_counter); 
0

공백이 아닌 문자의 개수를 알고 싶다면 도움이 될 것입니다.

String aString="Good Morning World!"; 
    int count=0; 
    for(int i=0;i<aString.length();i++){ 
     char c = aString.charAt(i); 
     if(c==' ') continue; 
     count++; 
    } 
    System.out.println("Total Length is:"+count); 
관련 문제