终止一个 char[] ->通过空指针进行中途字符串转换 [英] Terminate a char[] -> String conversion midway via a null pointer

查看:42
本文介绍了终止一个 char[] ->通过空指针进行中途字符串转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Java 中复制this.为了节省您的点击次数,它表示字符数组 ['F', 'R', 'A', 'N', 'K', NULL, 'k', 'e', 'f','w'],当转换为空终止字符串时,将在 'K' 之后停止,因为它在那里遇到了一个空指针.但是,我的 Java 尝试似乎不起作用.

I'm trying to replicate this in Java. To save you the click, it says that a character array ['F', 'R', 'A', 'N', 'K', NULL, 'k', 'e', 'f', 'w'], when converted to a null-terminated string, will stop after 'K', since it encounters a null pointer there. However, my Java attempts don't seem to be working.

public class TerminatingStrings{
    public static void main(String[] args){
        char[] broken = new char[3];
        broken[0] = 'a';
        broken[1] = '\u0000';
        broken[2] = 'c';
        String s = new String(broken);
        System.out.println(s);
    }
}

仍然打印ac.除此之外,我还尝试过 (1) 不初始化 broken[1] 和 (2) 将其显式设置为 null,尝试甚至没有编译.

Still prints ac. Aside from this I've also tried (1) not initializing broken[1] and (2) explicitly setting it to null, at attempt which didn't even compile.

这在 Java 中可能吗?或者我对事情的理解有误?

Is this possible at all in Java? Or maybe my understanding of things is wrong?

推荐答案

与 C 不同,Java 不使用以 NUL 结尾的字符串.要获得该行为,您的代码必须找到 char 数组中第一个 \0 的位置,并在构造字符串时停止.

Unlike C, Java does not use NUL-terminated strings. To get the behaviour, your code has to find the location of the first \0 in the char array, and stop there when constructing the string.

这篇关于终止一个 char[] ->通过空指针进行中途字符串转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆