Java 是否为空格等任何字符定义常量?

问题描述 投票:0回答:5

Java 是否包含任何单个字符的常量,例如 SPACE

在进行字符串操作时,从 Unicode 中获取名称会很方便。

我想要这个:

String musician = "Lisa" + Character.SPACE + "Coleman" ;

…而不是这个:

String musician = "Lisa" + " " + "Coleman" ;

(不要与 java.lang.Character 类混淆)

如果没有与 Java 捆绑在一起,还有其他选择吗?

java character constants
5个回答
22
投票

Apache Commons 中有一些

org.apache.commons.lang3.StringUtils.SPACE

更多


12
投票

不存在这样的常数,并且有充分的理由,IMO。

为什么在你的例子中首先使用常量?

String musician = "Lisa" + Character.SPACE + "Coleman" ;

可读性差
String musician = "Lisa Coleman";

甚至比

String musician = "Lisa" + ' ' + "Coleman";

所以我想这不是出于可读性原因。

因此我猜测您需要一个常量来避免在代码的多个部分中重复。但到处使用

Character.SPACE
代替
' '
并不会减少重复次数。仅适用于更冗长且可读性较差的代码。

因此,我猜测您希望能够在一处更改常量值,并在使用它的所有地方进行更改。但是使用内置的

Character.SPACE
常量将无法让您实现该目标。您仍然需要自己的常量,并且它的名称不应该是值是什么,而是值是什么 for:

private static final char FIRST_NAME_LAST_NAME_SEPARATOR = ' ';

现在,使用该常量有一个很好的理由:如果您稍后决定使用制表符而不是空格,则可以更改该常量的值并重新编译所有代码。


1
投票

Java 确实有一个字符常量列表,用于替换“不可输入的”字符,例如退格键(由 )。完整列表可以在https://docstore.mik.ua/orelly/java-ent/jenut/ch10_05.htm找到 不过,这里有一些例子:

\\      Backslash
\r      Carriage Return
\"      Double Quote (same for single Quote)
\n      Newline

你明白了。希望这就是您所寻找的,因为您确实在标题中提到了字符常量。

编辑:当使用字符常量时,字符用单引号而不是双引号括起来。尽管有两个(或更多)字符长,但它们表示单个字符或单个二进制数字而不是字符串。

注意:当尝试比较

java.awt.event.KeyListener
keyTyped 函数中的“enter”字符时,
\n
字符常量应该是用户而不是
\r
字符常量。


0
投票

使用 com.google.common.base.Ascii

String LINE_SEPARATOR = Character.toString((char) Ascii.LF);

0
投票

示例代码

这里的源代码为构成 Unicode 开头的 128 个 US-ASCII 字符定义了一个常量名称。

package work.basil.unicode;

@SuppressWarnings ( "unused" )
public final class Ascii
{
    public static final class Control
    {
        public static final String NULL = Character.toString ( 0 );
        public static final String START_OF_HEADING = Character.toString ( 1 );
        public static final String START_OF_TEXT = Character.toString ( 2 );
        public static final String END_OF_TEXT = Character.toString ( 3 );
        public static final String END_OF_TRANSMISSION = Character.toString ( 4 );
        public static final String ENQUIRY = Character.toString ( 5 );
        public static final String ACKNOWLEDGE = Character.toString ( 6 );
        public static final String BEL = Character.toString ( 7 );
        public static final String BACKSPACE = Character.toString ( 8 );
        public static final String CHARACTER_TABULATION = Character.toString ( 9 );
        public static final String LINE_FEED_LF = Character.toString ( 10 );
        public static final String LINE_TABULATION = Character.toString ( 11 );
        public static final String FORM_FEED_FF = Character.toString ( 12 );
        public static final String CARRIAGE_RETURN_CR = Character.toString ( 13 );
        public static final String SHIFT_OUT = Character.toString ( 14 );
        public static final String SHIFT_IN = Character.toString ( 15 );
        public static final String DATA_LINK_ESCAPE = Character.toString ( 16 );
        public static final String DEVICE_CONTROL_ONE = Character.toString ( 17 );
        public static final String DEVICE_CONTROL_TWO = Character.toString ( 18 );
        public static final String DEVICE_CONTROL_THREE = Character.toString ( 19 );
        public static final String DEVICE_CONTROL_FOUR = Character.toString ( 20 );
        public static final String NEGATIVE_ACKNOWLEDGE = Character.toString ( 21 );
        public static final String SYNCHRONOUS_IDLE = Character.toString ( 22 );
        public static final String END_OF_TRANSMISSION_BLOCK = Character.toString ( 23 );
        public static final String CANCEL = Character.toString ( 24 );
        public static final String END_OF_MEDIUM = Character.toString ( 25 );
        public static final String SUBSTITUTE = Character.toString ( 26 );
        public static final String ESCAPE = Character.toString ( 27 );
        public static final String INFORMATION_SEPARATOR_FOUR = Character.toString ( 28 );
        public static final String INFORMATION_SEPARATOR_THREE = Character.toString ( 29 );
        public static final String INFORMATION_SEPARATOR_TWO = Character.toString ( 30 );
        public static final String INFORMATION_SEPARATOR_ONE = Character.toString ( 31 );
        public static final String DELETE = Character.toString ( 127 );
    }
    public static final class Punctuation
    {
        public static final String SPACE = Character.toString ( 32 );
        public static final String EXCLAMATION_MARK = Character.toString ( 33 );
        public static final String QUOTATION_MARK = Character.toString ( 34 );
        public static final String NUMBER_SIGN = Character.toString ( 35 );
        public static final String PERCENT_SIGN = Character.toString ( 37 );
        public static final String AMPERSAND = Character.toString ( 38 );
        public static final String APOSTROPHE = Character.toString ( 39 );
        public static final String LEFT_PARENTHESIS = Character.toString ( 40 );
        public static final String RIGHT_PARENTHESIS = Character.toString ( 41 );
        public static final String ASTERISK = Character.toString ( 42 );
        public static final String COMMA = Character.toString ( 44 );
        public static final String HYPHEN_MINUS = Character.toString ( 45 );
        public static final String FULL_STOP = Character.toString ( 46 );
        public static final String SOLIDUS = Character.toString ( 47 );
        public static final String COLON = Character.toString ( 58 );
        public static final String SEMICOLON = Character.toString ( 59 );
        public static final String QUESTION_MARK = Character.toString ( 63 );
        public static final String COMMERCIAL_AT = Character.toString ( 64 );
        public static final String LEFT_SQUARE_BRACKET = Character.toString ( 91 );
        public static final String REVERSE_SOLIDUS = Character.toString ( 92 );
        public static final String RIGHT_SQUARE_BRACKET = Character.toString ( 93 );
        public static final String LOW_LINE = Character.toString ( 95 );
        public static final String LEFT_CURLY_BRACKET = Character.toString ( 123 );
        public static final String RIGHT_CURLY_BRACKET = Character.toString ( 125 );
    }
    public static final class Symbol
    {
        public static final String DOLLAR_SIGN = Character.toString ( 36 );
        public static final String PLUS_SIGN = Character.toString ( 43 );
        public static final String LESS_THAN_SIGN = Character.toString ( 60 );
        public static final String EQUALS_SIGN = Character.toString ( 61 );
        public static final String GREATER_THAN_SIGN = Character.toString ( 62 );
        public static final String CIRCUMFLEX_ACCENT = Character.toString ( 94 );
        public static final String GRAVE_ACCENT = Character.toString ( 96 );
        public static final String VERTICAL_LINE = Character.toString ( 124 );
        public static final String TILDE = Character.toString ( 126 );
    }
    public static final class Digit
    {
        public static final String DIGIT_ZERO = Character.toString ( 48 );
        public static final String DIGIT_ONE = Character.toString ( 49 );
        public static final String DIGIT_TWO = Character.toString ( 50 );
        public static final String DIGIT_THREE = Character.toString ( 51 );
        public static final String DIGIT_FOUR = Character.toString ( 52 );
        public static final String DIGIT_FIVE = Character.toString ( 53 );
        public static final String DIGIT_SIX = Character.toString ( 54 );
        public static final String DIGIT_SEVEN = Character.toString ( 55 );
        public static final String DIGIT_EIGHT = Character.toString ( 56 );
        public static final String DIGIT_NINE = Character.toString ( 57 );
    }
    public static final class Uppercase
    {
        public static final String LATIN_CAPITAL_LETTER_A = Character.toString ( 65 );
        public static final String LATIN_CAPITAL_LETTER_B = Character.toString ( 66 );
        public static final String LATIN_CAPITAL_LETTER_C = Character.toString ( 67 );
        public static final String LATIN_CAPITAL_LETTER_D = Character.toString ( 68 );
        public static final String LATIN_CAPITAL_LETTER_E = Character.toString ( 69 );
        public static final String LATIN_CAPITAL_LETTER_F = Character.toString ( 70 );
        public static final String LATIN_CAPITAL_LETTER_G = Character.toString ( 71 );
        public static final String LATIN_CAPITAL_LETTER_H = Character.toString ( 72 );
        public static final String LATIN_CAPITAL_LETTER_I = Character.toString ( 73 );
        public static final String LATIN_CAPITAL_LETTER_J = Character.toString ( 74 );
        public static final String LATIN_CAPITAL_LETTER_K = Character.toString ( 75 );
        public static final String LATIN_CAPITAL_LETTER_L = Character.toString ( 76 );
        public static final String LATIN_CAPITAL_LETTER_M = Character.toString ( 77 );
        public static final String LATIN_CAPITAL_LETTER_N = Character.toString ( 78 );
        public static final String LATIN_CAPITAL_LETTER_O = Character.toString ( 79 );
        public static final String LATIN_CAPITAL_LETTER_P = Character.toString ( 80 );
        public static final String LATIN_CAPITAL_LETTER_Q = Character.toString ( 81 );
        public static final String LATIN_CAPITAL_LETTER_R = Character.toString ( 82 );
        public static final String LATIN_CAPITAL_LETTER_S = Character.toString ( 83 );
        public static final String LATIN_CAPITAL_LETTER_T = Character.toString ( 84 );
        public static final String LATIN_CAPITAL_LETTER_U = Character.toString ( 85 );
        public static final String LATIN_CAPITAL_LETTER_V = Character.toString ( 86 );
        public static final String LATIN_CAPITAL_LETTER_W = Character.toString ( 87 );
        public static final String LATIN_CAPITAL_LETTER_X = Character.toString ( 88 );
        public static final String LATIN_CAPITAL_LETTER_Y = Character.toString ( 89 );
        public static final String LATIN_CAPITAL_LETTER_Z = Character.toString ( 90 );
    }
    public static final class Lowercase
    {
        public static final String LATIN_SMALL_LETTER_A = Character.toString ( 97 );
        public static final String LATIN_SMALL_LETTER_B = Character.toString ( 98 );
        public static final String LATIN_SMALL_LETTER_C = Character.toString ( 99 );
        public static final String LATIN_SMALL_LETTER_D = Character.toString ( 100 );
        public static final String LATIN_SMALL_LETTER_E = Character.toString ( 101 );
        public static final String LATIN_SMALL_LETTER_F = Character.toString ( 102 );
        public static final String LATIN_SMALL_LETTER_G = Character.toString ( 103 );
        public static final String LATIN_SMALL_LETTER_H = Character.toString ( 104 );
        public static final String LATIN_SMALL_LETTER_I = Character.toString ( 105 );
        public static final String LATIN_SMALL_LETTER_J = Character.toString ( 106 );
        public static final String LATIN_SMALL_LETTER_K = Character.toString ( 107 );
        public static final String LATIN_SMALL_LETTER_L = Character.toString ( 108 );
        public static final String LATIN_SMALL_LETTER_M = Character.toString ( 109 );
        public static final String LATIN_SMALL_LETTER_N = Character.toString ( 110 );
        public static final String LATIN_SMALL_LETTER_O = Character.toString ( 111 );
        public static final String LATIN_SMALL_LETTER_P = Character.toString ( 112 );
        public static final String LATIN_SMALL_LETTER_Q = Character.toString ( 113 );
        public static final String LATIN_SMALL_LETTER_R = Character.toString ( 114 );
        public static final String LATIN_SMALL_LETTER_S = Character.toString ( 115 );
        public static final String LATIN_SMALL_LETTER_T = Character.toString ( 116 );
        public static final String LATIN_SMALL_LETTER_U = Character.toString ( 117 );
        public static final String LATIN_SMALL_LETTER_V = Character.toString ( 118 );
        public static final String LATIN_SMALL_LETTER_W = Character.toString ( 119 );
        public static final String LATIN_SMALL_LETTER_X = Character.toString ( 120 );
        public static final String LATIN_SMALL_LETTER_Y = Character.toString ( 121 );
        public static final String LATIN_SMALL_LETTER_Z = Character.toString ( 122 );
    }
}

使用示例:

String helloWorld =
        Ascii.Uppercase.LATIN_CAPITAL_LETTER_H +
                Ascii.Lowercase.LATIN_SMALL_LETTER_E +
                Ascii.Lowercase.LATIN_SMALL_LETTER_L +
                Ascii.Lowercase.LATIN_SMALL_LETTER_L +
                Ascii.Lowercase.LATIN_SMALL_LETTER_O +
                Ascii.Punctuation.SPACE +
                Ascii.Uppercase.LATIN_CAPITAL_LETTER_W +
                Ascii.Lowercase.LATIN_SMALL_LETTER_O +
                Ascii.Lowercase.LATIN_SMALL_LETTER_R +
                Ascii.Lowercase.LATIN_SMALL_LETTER_L +
                Ascii.Lowercase.LATIN_SMALL_LETTER_D +
                Ascii.Punctuation.EXCLAMATION_MARK +
                Ascii.Control.LINE_FEED_LF +
                Ascii.Symbol.DOLLAR_SIGN +
                Ascii.Digit.DIGIT_ONE +
                Ascii.Digit.DIGIT_TWO +
                Ascii.Punctuation.FULL_STOP +
                Ascii.Digit.DIGIT_SEVEN +
                Ascii.Digit.DIGIT_ZERO +
                Ascii.Control.LINE_FEED_LF +
                Ascii.Symbol.GREATER_THAN_SIGN +
                Ascii.Control.LINE_FEED_LF +
                Ascii.Digit.DIGIT_ZERO;

System.out.println ( helloWorld );

奔跑。

Hello World!
$12.70
>
0

您可以访问任何这些字符的代码点。

Ascii.Uppercase.LATIN_CAPITAL_LETTER_A.codePointAt ( 0 )

65

生成器代码

这是我编写的用于生成上面看到的源代码的代码。

如果您想将结果调整为您自己对分隔符、名称、分组等的偏好,您可能会发现这很有用。

package work.basil.unicode;

import java.util.*;

/*
 Generates source code for a .java class filled with constants naming each of the 128 US-ASCII
 characters that make up beginning of Unicode.
 These constant names may be helpful to the developer seeking to avoid "magic numbers"
 in their code when working with individual code points.
 Tip: You can get the code point integer number for any of these constant strings:
 Ascii.Uppercase.LATIN_CAPITAL_LETTER_A.codePointAt ( 0 ) -> 65

 For reference, see Unicode Consortium document "C0 Controls and Basic Latin Range: 0000–007F"
 https://unicode.org/charts/PDF/U0000.pdf

 By Basil Bourque.
*/
public class AsciiGenerator
{
    // Fields
    private final SequencedCollection < Integer > control = new ArrayList <> ( );
    private final SequencedCollection < Integer > punctuation = new ArrayList <> ( );
    private final SequencedCollection < Integer > symbol = new ArrayList <> ( );
    private final SequencedCollection < Integer > digit = new ArrayList <> ( );
    private final SequencedCollection < Integer > uppercase = new ArrayList <> ( );
    private final SequencedCollection < Integer > lowercase = new ArrayList <> ( );
    private final SequencedCollection < SequencedCollection < Integer > > codePointGroups =
            List.of (
                    this.control ,
                    this.punctuation ,
                    this.symbol ,
                    this.digit ,
                    this.uppercase ,
                    this.lowercase
            );
    private final Map < SequencedCollection < Integer >, String > mapCodePointGroupToMethodName;

    // Constructor
    public AsciiGenerator ( )
    {
        this.populate ( );
        mapCodePointGroupToMethodName =
                Map.of (
                        this.control , "Control" ,
                        this.punctuation , "Punctuation" ,
                        this.symbol , "Symbol" ,
                        this.digit , "Digit" ,
                        this.uppercase , "Uppercase" ,
                        this.lowercase , "Lowercase"
                );
    }

    private void populate ( )
    {
        List < Byte > punctuationTypes = List.of (
                Character.CONNECTOR_PUNCTUATION ,
                Character.DASH_PUNCTUATION ,
                Character.END_PUNCTUATION ,
                Character.FINAL_QUOTE_PUNCTUATION ,
                Character.INITIAL_QUOTE_PUNCTUATION ,
                Character.OTHER_PUNCTUATION ,
                Character.START_PUNCTUATION );

        final int COUNT_OF_ASCII_CHARACTERS = 128;
        for ( int codePoint = 0 ; codePoint < COUNT_OF_ASCII_CHARACTERS ; codePoint++ )
        {
            switch ( Character.getType ( codePoint ) )
            {
                case Character.CONTROL -> this.control.add ( codePoint );
                case Character.CONNECTOR_PUNCTUATION ,
                        Character.DASH_PUNCTUATION ,
                        Character.END_PUNCTUATION ,
                        Character.FINAL_QUOTE_PUNCTUATION ,
                        Character.INITIAL_QUOTE_PUNCTUATION ,
                        Character.OTHER_PUNCTUATION ,
                        Character.START_PUNCTUATION ,
                        Character.SPACE_SEPARATOR -> this.punctuation.add ( codePoint );
                case Character.CURRENCY_SYMBOL ,
                        Character.MATH_SYMBOL ,
                        Character.MODIFIER_SYMBOL -> this.symbol.add ( codePoint );
                case Character.DECIMAL_DIGIT_NUMBER -> this.digit.add ( codePoint );
                case Character.LOWERCASE_LETTER -> this.lowercase.add ( codePoint );
                case Character.UPPERCASE_LETTER -> this.uppercase.add ( codePoint );
                default -> System.out.println ( "ERROR Unexpected codePoint = " + codePoint + " | type = " + Character.getType ( codePoint ) );
            }
        }
    }

    public void dump ( )
    {
        this.codePointGroups.forEach ( System.out :: println ); // Dump each collection of code points.
        int total = this.codePointGroups.stream ( ).mapToInt ( Collection :: size ).sum ( ); // Count all the code points across all the collecions. Should be 128.
        System.out.println ( "Total number of code points: " + total );
    }

    public String generateSourceCodeForClassOfConstants ( )
    {
        final String INDENT = " ".repeat ( 4 );  // Indent four SPACE characters. Or perhaps one TAB character, if you like.
        final String EOL = "\n";  // End-of-line terminator: LINE FEED. Or perhaps CR-LF, if you like.
        final StringBuilder sourceCode = new StringBuilder ( );
        sourceCode.append ( """
                package work.basil.unicode;
                          
                @SuppressWarnings ( "unused" )
                public final class Ascii
                {
                """ );
        for ( SequencedCollection < Integer > codePointGroup : codePointGroups )
        {
            String nestedClassName = mapCodePointGroupToMethodName.get ( codePointGroup );
            sourceCode
                    .append ( INDENT )
                    .append ( "public static final class " )
                    .append ( nestedClassName )
                    .append ( EOL )
                    .append ( INDENT )
                    .append ( "{" )
                    .append ( EOL );
            for ( Integer codePoint : codePointGroup )
            {
                String name =
                        Character
                                .getName ( codePoint )
                                .replace ( " " , "_" )
                                .replace ( "(" , "" ) // Delete parens from "LINE FEED (LF)", "FORM FEED (FF)", "CARRIAGE RETURN (CR).
                                .replace ( ")" , "" )
                                .replace ( "-" , "_" ) // Replace "-" in "HYPHEN-MINUS" with "_" (LOW LINE).
                        ;
                sourceCode
                        .append ( INDENT.repeat ( 2 ) )
                        .append ( "public static final String " )
                        .append ( name )
                        .append ( " = Character.toString ( " )
                        .append ( codePoint )
                        .append ( " );" )
                        .append ( EOL )
                ;
            }
            sourceCode
                    .append ( INDENT )
                    .append ( "}" )
                    .append ( EOL );
        }
        sourceCode.append ( "}" );
        return sourceCode.toString ( );
    }

    public static void main ( String[] args )
    {
        AsciiGenerator asciiGenerator = new AsciiGenerator ( );
        asciiGenerator.dump ( );
        System.out.println ( "-----------|  Class Source Code  |-----------------" );
        System.out.println ( asciiGenerator.generateSourceCodeForClassOfConstants ( ) );
        System.out.println ( "-----------|  end  |-----------------" );
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.