Programing

문자가 빈 공간과 같은지 확인하는 방법은 무엇입니까?

lottogame 2020. 8. 27. 08:06
반응형

문자가 빈 공간과 같은지 확인하는 방법은 무엇입니까?


내가 가진 것은 다음과 같습니다.

private static int countNumChars(String s) {
    for(char c : s.toCharArray()){
        if (Equals(c," "))
    }
}

그러나 해당 코드는 해당 메서드에 대한 Symbol을 찾을 수 없다고 말합니다. 나는 자바가 이와 같은 비교자를 가지고있는 것을 기억한다.


if (c == ' ')

char는 원시 데이터 유형이므로 ==.

또한 큰 따옴표를 사용하여 String상수 ( " ") 를 만들고 작은 따옴표를 사용 하면 char상수 ( ' ')입니다.


필요한 코드는 "빈 공간"이 의미하는 바에 따라 다릅니다.

  • ASCII / Latin-1 / 유니 코드 공백 문자 (0x20) 일명 SP를 의미하는 경우 :

    if (ch == ' ') {
        // ...
    }
    
  • 기존 ASCII 공백 문자 (SP, HT, VT, CR, NL)를 의미하는 경우 :

    if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '\x0b') {
        // ...
    }
    
  • 유니 코드 공백 문자를 의미하는 경우 :

    if (Character.isWhitespace(ch)) {
        // ...
    }
    

유니 코드 공백에는 추가 ASCII 제어 코드 상위 코드 플레인의 다른 유니 코드 문자가 포함됩니다. 에 대한 javadoc을 참조하십시오 Character.isWhitespace(char).


당신이 쓴 것은 다음과 같습니다.

    if (Equals(ch, " ")) {
        // ...
    }

이것은 여러 수준에서 잘못된 것입니다. 첫째, Java 컴파일러가이를 시그니처가있는 메서드에 대한 호출로 해석하려고 시도하는 방식입니다 boolean Equals(char, String).

  • 컴파일러가 오류 메시지에보고 한대로 메서드가 없기 때문에 잘못된 것입니다.
  • Equals어쨌든 일반적으로 메소드의 이름이 아닙니다. Java 규칙은 메소드 이름이 소문자로 시작한다는 것입니다.
  • 코드는 (서면으로) 문자와 문자열을 비교하려고하지만, 한 charString비교할 수 없습니다 공통 기본 형식으로 캐스팅 할 수 없습니다.

Java에는 Comparator와 같은 것이 있지만 메서드가 아닌 인터페이스이며 다음과 같이 선언됩니다.

    public interface Comparator<T> {
        public int compare(T v1, T v2);
    }

즉, 메서드 이름은 compare(아님 Equals)이고 정수 (부울 아님)를 반환하며 유형 매개 변수가 제공하는 유형으로 승격 될 수있는 두 값을 비교합니다.


누군가 (삭제 된 답변에서!)는 이것을 시도했다고 말했습니다.

    if (c == " ")

두 가지 이유로 실패합니다.

  • " "문자 리터럴이 아닌 문자열 리터럴이며 Java는 Stringchar값의 직접 비교를 허용하지 않습니다 .

  • You should NEVER compare Strings or String literals using ==. The == operator on a reference type compares object identity, not object value. In the case of String it is common to have different objects with different identity and the same value. An == test will often give the wrong answer ... from the perspective of what you are trying to do here.


You could use

Character.isWhitespace(c)

or any of the other available methods in the Character class.

  if (c == ' ')

also works.


Since char is a primitive type, you can just write c == ' '.
You only need to call equals() for reference types like String or Character.


To compare character you use the == operator:

if (c == ' ')

My suggestion would be:

if (c == ' ')

In this case, you are thinking of the String comparing function "String".equals("some_text"). Chars do not need to use this function. Instead a standard == comparison operator will suffice.

private static int countNumChars(String s) {
    for(char c : s.toCharArray()){
        if (c == ' ') // your resulting outcome
    }
}

Character.isSpaceChar(c) || Character.isWhitespace(c) worked for me.


At first glance, your code will not compile. Since the nested if statement doesn't have any braces, it will consider the next line the code that it should execute. Also, you are comparing a char against a String, " ". Try comparing the values as chars instead. I think the correct syntax would be:

if(c == ' '){
   //do something here
}

But then again, I am not familiar with the "Equal" class


You can try:

if(Character.isSpaceChar(ch))
{
    // Do something...
}

Or:

if((int) ch) == 32)
{
    // Do something...
}

To compare Strings you have to use the equals keyword.

if(c.equals(""))
{
}

참고URL : https://stackoverflow.com/questions/4510136/how-to-check-if-a-char-is-equal-to-an-empty-space

반응형