java - 是否可以避免将相同的元素打印到数组中
问题描述
我尝试创建许多变体,尝试切换嵌套的 for 循环,并尝试将其存储在临时值中,但要知道是否有用,这是我的原始代码的测试代码,它将调用多种方法,我不希望它得到覆盖
public class Main {
public static void main(String[] args) {
char[] memoryArray = new char[24];
String s = new String("hello");
int start = 0;
int length = s.length();
String d = new String("world");
int length1 = d.length();
char tmp;
for (int i = start; i < length - start; i++) {
if (memoryArray[i] == '\u0000') {
memoryArray[i] = s.charAt(i);
}
}
start = start + length;
for (int i = 0; i < length1; i++) {
tmp = d.charAt(i);
for (int j = start; j < start + length1; j++)
if (memoryArray[j] == '\u0000') {
memoryArray[j] = tmp;
}
}
System.out.println(memoryArray);
}
}
预期输出 helloworld
解决方案
在您的特定情况下,您知道这两个字符串是什么,hello
和world
,但是如果您不知道这些变量将包含什么字符串怎么办?
创建数组的最简单解决方案是:
- 将字符串连接在一起形成一个新的字符串变量;
- 声明
memoryArray
并将新连接字符串中的每个字符放入该数组中; - 显示 的内容
memoryArray
。
考虑到这一点:
String a = "hello";
String b = "programming";
String c = "world";
// Concatenate the strings together
String newString = new StringBuilder(a).append(b).append(c).toString();
// Declare memoryArray and fill with the characters from newString.
char[] memoryArray = newString.toCharArray();
// Display the Array contents
System.out.println(memoryArray);
但是,如果您想for
为此类事情使用循环,那么这些步骤可以解决问题:
- 将字符串连接成一个
newString
字符串变量; - 声明
memoryArray
并根据newString
长度进行初始化; - 创建一个
for
循环以一次遍历newString
一个字符; - 在循环中,将每个字符添加到
memoryArray
字符数组中; - 显示 的内容
memoryArray
。
考虑到这一点:
String a = "hello";
String b = "programming";
String c = "world";
// Concatenate the strings together
String newString = new StringBuilder(a).append(b).append(c).toString();
// Declare and initialize the memoryArray array based on the length of newString.
char[] memoryArray = new char[newString.length()];
// Iterate through newString and fill memoryArray
for (int i = 0; i < newString.length(); i++) {
memoryArray[i] = newString.charAt(i);
}
// Display the Array contents
System.out.println(memoryArray);
推荐阅读
- javascript - 在 Angular 中将同步函数修改为异步函数
- reactjs - “在'@superset-ui/core'中找不到导出'Metric'(./node_modules/@superset-ui/chart-controls/esm/types.js 中的错误)Angular/React
- django - 为什么 Django 检索所有反向异物
- javascript - 如何在 nuxt auth 模块中发送 refreshToken 和 token?
- linux - 在不同的机器上在 valgrind 下运行太慢 - 在 strace'ing 进程时已修复?
- javascript - 什么是创建递归函数上限的好方法和好语言?
- asp.net-core - 从第 3 方 websocket 流出并流出 SignalR 集线器
- javascript - 为什么 ko.ObservableArray 中的替换值没有更新我的视图?
- javascript - 无法读取 client.users 的属性“缓存”
- react-native - react native asyncStorage 更新相同的产品编号