developer tip

Java Character 클래스에서 빈 문자를 나타내는 방법

copycodes 2020. 8. 17. 09:14
반응형

Java Character 클래스에서 빈 문자를 나타내는 방법


Java ""에서 String 과 같이 빈 문자를 나타내고 싶습니다 .

그렇게 char ch = an empty character;

사실 공백없이 문자를 바꾸고 싶습니다.

나는 이것이 의미하는 바를 이해하는 것으로 충분할 것이라고 생각합니다.


할당 할 수 있습니다 '\u0000'(또는 0). 이를 위해 Character.MIN_VALUE.

Character ch = Character.MIN_VALUE;

char정확히 한 문자를 의미합니다. 이 유형에는 0 개의 문자를 할당 할 수 없습니다.

이는 String.replace(char, char)길이가 다른 문자열을 반환하는 char 값이 없음을 의미합니다 .


Character는 Object에서 파생 된 클래스이므로 null을 "인스턴스"로 할당 할 수 있습니다.

Character myChar = null;

문제 해결됨 ;)


빈 문자열은 char[]요소가없는 래퍼입니다 . 비어있을 수 있습니다 char[]. 그러나 당신은 "빈"을 가질 수 없습니다 char. 다른 프리미티브와 마찬가지로 a char는 값을 가져야합니다.

"공백을 남기지 않고 문자를 교체"하고 싶다고합니다.

를 다루는 경우 해당 요소가 제거 char[]된 새 파일 char[]만듭니다 .

를 처리하는 경우 문자가 제거 String된 새 String(String is immutable)를 만듭니다 .

다음은 문자를 제거하는 방법에 대한 몇 가지 샘플입니다.

public static void main(String[] args) throws Exception {

    String s = "abcdefg";
    int index = s.indexOf('d');

    // delete a char from a char[]
    char[] array = s.toCharArray();
    char[] tmp = new char[array.length-1];
    System.arraycopy(array, 0, tmp, 0, index);
    System.arraycopy(array, index+1, tmp, index, tmp.length-index);
    System.err.println(new String(tmp));

    // delete a char from a String using replace
    String s1 = s.replace("d", "");
    System.err.println(s1);

    // delete a char from a String using StringBuilder
    StringBuilder sb = new StringBuilder(s);
    sb.deleteCharAt(index);
    s1 = sb.toString();
    System.err.println(s1);

}

빈 공간을 남기지 않고 문자열의 문자를 바꾸려면 StringBuilder를 사용하면됩니다. 문자열은 Java에서 변경 불가능한 객체이므로 수정할 수 없습니다.

String str = "Hello";
StringBuilder sb = new StringBuilder(str);
sb.deleteCharAt(1); // to replace e character

chars정수 (ASCII- 코드)로 표현할 수있는 것처럼 간단히 다음과 같이 작성할 수 있습니다.

char c = 0;

ASCII 코드의 0은 null입니다.


당신은 할 수 없습니다. ""포함하지 않는 문자열에 대한 리터럴 에는 문자. "빈 문자"(당신이 의미하는 바에 상관없이)를 포함하지 않습니다.


자바에서는 빈 문자 리터럴 만큼 아무것도 없습니다. 즉, ''는 빈 문자열 리터럴 을 의미하는 ""와 달리 의미가 없습니다.

빈 문자 리터럴을 나타내는 가장 가까운 방법은 길이가 0 인 char []입니다.

char[] cArr = {};         // cArr is a zero length array
char[] cArr = new char[0] // this does the same

String 클래스를 참조하면 기본 생성자가 다음을 사용하여 빈 문자 시퀀스를 만듭니다. new char[0]

Also, using Character.MIN_VALUE is not correct because it is not really empty character rather smallest value of type character.

I also don't like Character c = null; as a solution mainly because jvm will throw NPE if it tries to un-box it. Secondly, null is basically a reference to nothing w.r.t reference type and here we are dealing with primitive type which don't accept null as a possible value.

Assuming that in the string, say str, OP wants to replace all occurrences of a character, say 'x', with empty character '', then try using:

str.replace("x", "");

this is how I do it.

char[] myEmptyCharArray = "".toCharArray();

char ch = Character.MIN_VALUE;

The code above will initialize the variable ch with the minimum value that a char can have (i.e. \u0000).


I was looking for this. Simply set the char c = 0; and it works perfectly. Try it.

For example, if you are trying to remove duplicate characters from a String , one way would be to convert the string to char array and store in a hashset of characters which would automatically prevent duplicates.

Another way, however, will be to convert the string to a char array, use two for-loops and compare each character with the rest of the string/char array (a Big O on N^2 activity), then for each duplicate found just set that char to 0..

...and use new String(char[]) to convert the resulting char array to string and then sysout to print (this is all java btw). you will observe all chars set to zero are simply not there and all duplicates are gone. long post, but just wanted to give you an example.

so yes set char c = 0; or if for char array, set cArray[i]=0 for that specific duplicate character and you will have removed it.


You can only re-use an existing character. e.g. \0 If you put this in a String, you will have a String with one character in it.


Say you want a char such that when you do

String s = 
char ch = ?
String s2 = s + ch; // there is not char which does this.
assert s.equals(s2);

what you have to do instead is

String s = 
char ch = MY_NULL_CHAR;
String s2 = ch == MY_NULL_CHAR ? s : s + ch;
assert s.equals(s2);

Use the \b operator (the backspace escape operator) in the second parameter

String test= "Anna Banana";

System.out.println(test); //returns Anna Banana<br><br>
System.out.println(test.replaceAll(" ","\b")); //returns AnnaBanana removing all the spaces in the string

Hey i always make methods for custom stuff that is usually not implemented in java. Here is a simple method i made for removing character from String Fast

    public static String removeChar(String str, char c){
        StringBuilder strNew=new StringBuilder(str.length());
        char charRead;
        for(int i=0;i<str.length();i++){
            charRead=str.charAt(i);
            if(charRead!=c)
                strNew.append(charRead);
        }
        return strNew.toString();
    }

For explaintion, yes there is no null character for replacing, but you can remove character like this. I know its a old question, but i am posting this answer because this code may be helpful for some persons.


Wrong:

String.replace('T', '') ;

Correct:

String.replace("T", "");

You can do something like this:

mystring.replace(""+ch, "");

참고URL : https://stackoverflow.com/questions/8534178/how-to-represent-empty-char-in-java-character-class

반응형