简体   繁体   English

我试图将一个字符串字符插入另一个字符串。 如何在Java中实现?

[英]I am trying to insert a string character to another string. How can I achieve it in java?

This is the code I am working upon. 这是我正在处理的代码。 I dont know where I am going wrong. 我不知道我要去哪里错了。

package mcdcpairwise;
import java.io.*;
import java.util.*;

public class Permutation
{
    public static void main(String[] args)
    {
        String a="000";
        String b="|&";

        for (int i=0; i < a.length(); i++){
            if (i % 2 != 0){
                a = a.substring(0,i-1) + b.substring(0,i-1). + a.substring(i, a.length()) + b.substring(i, b.length());
                System.out.println(a);
            }
        }

    }
}    

The error I am facing is: 我面临的错误是:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -2 at java.lang.String.substring(String.java:1967) at mcdcpairwise.Permutation.main(Permutation.java:13) 线程“主”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:java.lang.String.substring(String.java:1967)处为-2,mcdcpairwise.Permutation.main(Permutation.java:13)

The output should be : 输出应为:

0|0&0 0 | 0&0

正确的代码应该是a.substring(0,i)

It isn't clear from your question exactly what your "rules" are for processing this. 从您的问题中还不清楚您处理该规则的确切“规则”是什么。 However, your output seems to simply insert a character between each character of your source a string. 但是,您的输出似乎只是在源a每个字符之间插入a字符串。

Instead of using a substring, create a separate StringBuilder to add individual characters to. 代替使用子字符串,创建一个单独的StringBuilder可以向其中添加各个字符。 The code below produces the output you are looking for: 下面的代码产生您想要的输出:

String string = "000";
StringBuilder output = new StringBuilder();

for (int i = 0; i < string.length(); i++) {

    // Get current character in the string
    char c = string.charAt(i);

    // Add the current character to the output
    output.append(c);

    // If more characters exist, add the pipe
    if (i != string.length() - 1) {
        output.append("|");
    }
}

System.out.println(output.toString());

You can use String.toCharArray to get a char[] from a String . 您可以使用String.toCharArrayString获取char[] That way we can iterate more easily both String using an index. 这样,我们可以使用索引更轻松地迭代两个String

String a="000";
String b="|&";

char[] arrayA = a.toCharArray();
char[] arrayB = b.toCharArray();

Then, all we have to do is to merge two array (from String s) taking one character from both. 然后,我们要做的就是合并两个数组(来自String ),从两个数组中取一个字符。 Adding two conditions (one per array) to prevent any ArrayIndexOutOfBOundsException, we can insure we will merge two arrays. 添加两个条件(每个数组一个)以防止任何ArrayIndexOutOfBOundsException,我们可以确保我们将合并两个数组。

StringBuilder sb = new StringBuilder();

//Add a char from both array (until we reach on of the limit)
int i = 0;
while( i < arrayA.length && i < arrayB.length){
    sb.append(arrayA[i]).append(arrayB[i]);
    ++i;
}

Then we just need to add the remaining characters using a for loop on both arrays. 然后,我们只需要在两个数组上使用for循环添加其余字符。 Only one of those loop will be triggered (or none) since at least one previous condition ( i < arrayA.length && i < arrayB.length ) is already false . 因为至少一个先前条件( i < arrayA.length && i < arrayB.length )已经为false所以将仅触发(或不触发)这些循环中的一个。

//Add the rest of `a` if any
for(int j = i; j < arrayA.length; ++j){
    sb.append(arrayA[j]);
}

//Add the rest of `b` if any
for(int j = i; j < arrayB.length; ++j){
    sb.append(arrayB[j]);
}

System.out.println(sb.toString());

0|0&0 0 | 0&0

Here's a one line solution: 这是一种解决方案:

System.out.println((a + b).replaceAll("(?<=.)(?=.{" + (a.length() - 1) + "}(.))|.(?=.{0," + (b.length() - 1) + "}$)", "$1"));

This works with all combinations of non-blank starting strings. 这适用于所有非空白起始字符串的组合。

See live demo . 观看现场演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我试图从字符串中拉出一个随机字。 Java的 - I'm trying to pull a random word from a string. Java 当我在 Java 中读取 API 时,我在字符串中使用 ÃŽ 代替 Î。 我该怎么办? - When I am reading a API in java I get ÃŽ in place of Î in a string. What should I do? Java字符串压缩输出错误的字符串。 我在这里想念什么? - Java string compression is printing wrong string. What am I missing here? 错误“不是 JSONObject”:在字符串中返回此格式的 API。 如何使用 Java 从中读取和创建对象? - Error "is not a JSONObject": an API that returns this format in a String. How can I read and create objects from this with Java? 如何将一个字符串的第一个字符与 Java 中另一个字符串的第 5 个字符进行比较? 并检查它们是否相同。我收到如下错误 - how to compare first character of one string to 5th char of another string in Java? and check if they are same.I am getting error as below 如何将对象类型的数组存储为字符串,以便另一个类以后可以调用并打印该字符串。 爪哇 - How to store an array of object types as a string so another class can later call and print that string. java 将字符串中的第一个字母大写。 我究竟做错了什么? - Capitalizing the first letter in a string. What am I doing wrong? 我正在尝试使用一个辅助程序来编写一个递归静态方法,以反转一个字符串。 为什么我会得到“堆栈溢出”? - I'm trying to write a recursive static method with a helper in order to reverse a string. Why am I getting “stack overflow?” 在 java 中,如何在另一个字符串数组中搜索字符串数组? - In java, how can i search String array in another String array? 如何在Java中的字符串中添加换行符? - How can I add a newline character to a String in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM