如何将字符串转换为数组/arraylist
我有这个代码要转换一个字符串(例如[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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不需要字节。 Java很好地处理文字。
使用
字符串#split
制作零件的数组。制作一系列字符串零件的流。
使用
对象使用
流#映射
将每个字符串
零件分为integer
对象,以制造新对象的另一个流。将这些新的
整数
对象收集到未约化的list
中。请参阅此 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 aInteger
object usingStream#map
to make another stream of the new objects.Collect these new
Integer
objects into an unmodifiableList
.See this code run live at Ideone.com.