如何将字符串转换为数组/arraylist

发布于 2025-02-13 22:04:54 字数 721 浏览 1 评论 0原文

我有这个代码要转换一个字符串(例如[15,52,94,20,92,109]) 到一个数组/阵列列表。

我尝试了此代码:

ArrayList<Byte> sdata = new ArrayList<>();
String bytessonvert = new String();
boolean run = true;
System.out.println("Enter Data: ");
String bytes = input.nextLine();
Bytes = bytes.substring(1, bytes.length());
for (int i = 0; i < bytes.length(); i++) {
    if (Objects.equals(bytes.substring(i, i), " ")) {
        sdata.add((byte) Integer.parseInt(bytessonvert));
        bytessonvert = "";
    } else if (bytes.substring(i, i) == ",") {
        sdata.add((byte) Integer.parseInt(bytessonvert));
        bytessonvert = "";
    } else {
        bytessonvert = bytessonvert + bytes.substring(i, i);
    }
}

I have this code in which I want to convert a String (e.g. [15, 52, 94, 20, 92, 109])
to an Array/ArrayList.

I have tried this code:

ArrayList<Byte> sdata = new ArrayList<>();
String bytessonvert = new String();
boolean run = true;
System.out.println("Enter Data: ");
String bytes = input.nextLine();
Bytes = bytes.substring(1, bytes.length());
for (int i = 0; i < bytes.length(); i++) {
    if (Objects.equals(bytes.substring(i, i), " ")) {
        sdata.add((byte) Integer.parseInt(bytessonvert));
        bytessonvert = "";
    } else if (bytes.substring(i, i) == ",") {
        sdata.add((byte) Integer.parseInt(bytessonvert));
        bytessonvert = "";
    } else {
        bytessonvert = bytessonvert + bytes.substring(i, i);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

隱形的亼 2025-02-20 22:04:54

不需要字节。 Java很好地处理文字。

使用字符串#split制作零件的数组。

制作一系列字符串零件的流。

使用对象使用流#映射将每个字符串零件分为integer对象,以制造新对象的另一个流。

将这些新的整数对象收集到未约化的list中。

List < Integer > integers = 
    Arrays
    .stream( 
        "15, 52, 94, 20, 92, 109".split( ", " ) 
    )
    .map( Integer :: valueOf )
    .toList() ;

请参阅此 code在indeone.com 中实时运行。

No need for bytes. Java handles text well.

Use String#split to make an array of the parts.

Make a stream of that array of string parts.

Parse each String part into a Integer object using Stream#map to make another stream of the new objects.

Collect these new Integer objects into an unmodifiable List.

List < Integer > integers = 
    Arrays
    .stream( 
        "15, 52, 94, 20, 92, 109".split( ", " ) 
    )
    .map( Integer :: valueOf )
    .toList() ;

See this code run live at Ideone.com.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文