首页 > 解决方案 > 是否可以避免将相同的元素打印到数组中

问题描述

我尝试创建许多变体,尝试切换嵌套的 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

标签: javaarrays

解决方案


在您的特定情况下,您知道这两个字符串是什么,helloworld,但是如果您不知道这些变量将包含什么字符串怎么办?

创建数组的最简单解决方案是:

  1. 将字符串连接在一起形成一个新的字符串变量;
  2. 声明memoryArray并将新连接字符串中的每个字符放入该数组中;
  3. 显示 的内容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为此类事情使用循环,那么这些步骤可以解决问题:

  1. 将字符串连接成一个newString字符串变量;
  2. 声明memoryArray并根据newString长度进行初始化;
  3. 创建一个for循环以一次遍历newString 一个字符;
  4. 在循环中,将每个字符添加到memoryArray字符数组中;
  5. 显示 的内容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);

推荐阅读