Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java中的字符串空间计数_Java_String - Fatal编程技术网

Java中的字符串空间计数

Java中的字符串空间计数,java,string,Java,String,问题很简单 abcd.length==4 而且,打印时需要4个空格 那么,这个怎么样 漢語.长度==2 但它需要4个空间 是否有任何库或方法来计算每种语言的空间? 我不想要一些图形化的方法 使现代化 例如。字眼안녕abc按System.out.println占用7个空格 ------- 안녕abc String.length() : 5 假设你指的是字节和空格 System.out.println( "漢語".getBytes().length ); // -> 6 其中String.

问题很简单

abcd.length==4

而且,打印时需要4个空格

那么,这个怎么样

漢語.长度==2

但它需要4个空间

是否有任何库或方法来计算每种语言的空间? 我不想要一些图形化的方法

使现代化 例如。字眼안녕abc按System.out.println占用7个空格

-------
안녕abc
String.length() : 5

假设你指的是字节和空格

System.out.println( "漢語".getBytes().length ); // -> 6
其中String.length返回字符序列2的长度

打印字符所需的可测量空间取决于使用的字体

使用对象,您可以使用字体度量来计算:

g.setFont(new Font("SomeSuitableFont", Font.BOLD, 24));
int width = g.getFontMetrics().stringWidth("漢語");

您希望字符串的显示宽度以空格为单位

取决于字体。有时,对于亚洲脚本,采用其他字体或字体大小。在某些字体中,空格可能非常窄。n-width是用于比较的更常用的度量

public static double spaceWidth(Font font, String text) {
    FontRenderContext frc = new FontRenderContext(font.getTransform(), true, true);
    Rectangle2D textRect = font.getStringBounds(text, frc);
    Rectangle2D spaceRect = font.getStringBounds(" ", frc);
    return textRect.getWidth() / spaceRect.getWidth();
}  

public static void main(String[] args) {
    Font font = new Font("Monospaced", Font.PLAIN, 10);
    System.out.println("Font: " + font.getFamily());

    String s = "안녕abc";
    //         "      " (6 spaces)
    System.out.printf("'%s' -> %f%n", s, spaceWidth(font, s));
}
6.332791

数学四舍五入会把事情综合起来。如您所见,即使字体是单间距的,也不会给出精确的6个空格


对于表格输出,最好将HTML与表格等一起使用。

为什么说它需要4个空格?拼音为汉语,共5个字符,共有2个汉字。文档: