【问题标题】:Most basic way to insert a character into a string in Java?在Java中将字符插入字符串的最基本方法?
【发布时间】:2016-01-08 23:19:16
【问题描述】:

假设我有一个字符串 x,我想添加一些字符 x 次数,以便字符串 x 的长度为 y,我该怎么做?

String x = "this_is_a_line";
//x.length() = 14;
length y = 20;
//insert character into line so String x becomes balanced to:
x = "this___is___a___line";
//x.length() = 20;

另一个例子:

String y = "in_it_yeah";
//y.length() = 10
length j = 15;
//inserting characters so String y becomes balanced to:
y = "in____it___yeah";

我想避免使用 StringBuilder 来追加字符。

我的思考过程:

  1. 创建一个长度为 y 的 Char 数组。
  2. 将字符串复制到数组中。
  3. 尝试逐个移动字符 从最右边的字符开始。

【问题讨论】:

  • 为什么是"this is a line" 而不是"this is a line"? (啊,空格删除!)你的逻辑是什么?在发布问题之前您尝试了什么?
  • StringBuilder;建立一个char[]String#substring
  • 这里的 cmets 删除了 whitepsace,因此格式不正确。我在问你如何决定空白应该去哪里?均匀?往前,往后?你的算法逻辑是什么?你试过实现它吗?
  • 如果你的字符串是a____b_c(长度为8)怎么办?如果所需长度为 9,是否应将其平衡到 a___b___c(请注意,之前在 ab 之间有 4 个空格,现在是 3 个)?
  • 为什么要避免使用StringBuilder?一种解决方案是将 StringBuilder 的源代码复制到另一个文件中,另存为 MyStringBuilder,进行必要的修改以确保它可以编译,然后使用 MyStringBuilder。

标签: java string character


【解决方案1】:

我希望我理解正确,但我认为这段代码可以满足你的要求。

编辑:这个会平均分配指定的字符,如果字符串不够长,可以创建像“a__b_c”这样的字符串。

import java.util.ArrayList;

public class Main {

public static void main(String[] args) {
    String string = "this_is_a_line";

    int length = string.length();
    int desiredLength = 16;
    int extraLengthRequired = desiredLength - length;

    char characterToBeDuplicated = '_';

    String[] rawPieces = string.split(Character.toString(characterToBeDuplicated));

    ArrayList<String> pieces = new ArrayList<>();
    int emptyIndexes = 0;

    for (String piece : rawPieces) {
        if(piece.equals("")) {
            emptyIndexes++;
        } else {
            pieces.add(piece);
        }
    }

    int numOfCharactersToBeMultiplied = pieces.size() - 1;

    int numOfMultiplications = (int) Math.floor((extraLengthRequired + emptyIndexes) / numOfCharactersToBeMultiplied) + 1;

    int lengthLeft = (extraLengthRequired + emptyIndexes) % numOfCharactersToBeMultiplied;

    String newString = pieces.get(0);

    for (int i = 1; i < pieces.size(); i++) {
        newString += characterToBeDuplicated;
        if(lengthLeft > 0) {
            newString += characterToBeDuplicated;
            lengthLeft--;
        }
        for (int j = 1; j < numOfMultiplications; j++) {
            newString += characterToBeDuplicated;
        }
        newString += pieces.get(i);
    }

    System.out.println(newString + " - " + newString.length());
}
}

旧解决方案:

public class Main {

public static void main(String[] args) {
    String string = "this_is_a_line";

    int length = string.length();
    int desiredLength = 20;
    int extraLengthRequired = desiredLength - length;

    char characterToBeDuplicated = '_';

    String[] pieces = string.split(Character.toString(characterToBeDuplicated));

    int numOfCharactersToBeMultiplied = pieces.length - 1;

    int numOfMultiplications = (int) Math.floor(extraLengthRequired / numOfCharactersToBeMultiplied);

    String newString = pieces[0];

    for (int i = 1; i < pieces.length; i++) {
        newString += characterToBeDuplicated;
        for (int j = 1; j < numOfMultiplications; j++) {
            newString += characterToBeDuplicated;
        }
        newString += pieces[i];
    }

    System.out.println(newString);
}

}

【讨论】:

  • 它不适用于 a____b_c(长度 8),从 OP 的 comment 开始,它应该是 a___b___c,长度为 9。长度为 10 时,它应该是 @987654326 @(4 个空格,然后是 3 个)
  • 对此我很抱歉,虽然 OP 本来可以更清楚一点。而且我认为这个例子可能使他能够完全按照自己的意愿去做。我以后可能会尝试自己修复它。
【解决方案2】:

我这样做是因为当我开始编写伪代码时,这对我来说有点挑战性,尽管我不喜欢在“gimme teh codez”上回答这样的问题。

我建议您在 for 循环内的字符串连接上使用 StringBuilder,因为它比使用 += 的实际字符串连接更有效。

注意:

  • 这个程序在末尾添加空格,这就是我打印它的长度修剪的原因。
  • 我使用正则表达式 \\s+ 而不是 _ 将其按空格分隔,因为这是您第一次写它的方式

以下代码适用于

a____b_c -> a___b___c (Lenght 9)
a____b_c -> a____b___c (Lenght 10)
this_is_a_line -> this___is___a___line (Lenght 20)
in_it_yeah -> in____it___yeah (Length 15)

代码:

class EnlargeString {
    public static void main (String args[]) {
        String x = "a    b c";
        int larger = 10;
        int numberOfSpaces = 0;
        String s[] = x.split("\\s+"); //We get the number of words

        numberOfSpaces = larger - s.length; //The number of spaces to be added after each token

        int extraSpaces = numberOfSpaces % s.length; //Extra spaces for the cases of 4 spaces then 3 or something like that

        System.out.println(extraSpaces);

        String newSpace[] = new String[s.length]; //The String array that will contain all string between words

        for (int i = 0; i < s.length; i++) {
            newSpace[i] = " "; //Initialize the previous array
        }

        //Here we add the extra spaces (the cases of 4 and 3)
        for (int i = 0; i < s.length; i++) {
            if (extraSpaces == 0) {
                break;
            }
            newSpace[i] += " ";
            extraSpaces--;
        }

        for (int i = 0; i < s.length; i++) {
            for (int j = 0; j < totalSpaces / s.length; j++) {
                newSpace[i] += " "; //Here we add all the equal spaces for all tokens
            }
        }

        String finalWord = "";
        for (int i = 0; i < s.length; i++) {
            finalWord += (s[i] + newSpace[i]); //Concatenate
        }
        System.out.println(x);
        System.out.println(x.length());
        System.out.println(finalWord);
        System.out.println(finalWord.trim().length());
    }
}

下次尝试自己做 1 次并展示 您的 逻辑,那么您的问题将得到更好的接受(可能是赞成票而不是反对票)这称为 Runnable Example。我也推荐你看看String concatenation vs StringBuilderHow to ask a good question,你也可以看看Take the tour

【讨论】:

  • 谢谢,我会自己尝试,这个问题已经让我发疯了两天,我需要改变我的逻辑,因为它不起作用。
【解决方案3】:

这是我的解决方案:

public class Main
{
    public static void main(String args[]){

        System.out.print("#Enter width : " );
        int width = BIO.getInt();

        System.out.print("#Enter line of text : " );
        String line = BIO.getString().trim();

        int nGaps, spToAdd, gapsLeft, modLeft, rem;
        nGaps = spToAdd = gapsLeft = rem = 0;

        double route = 0;
        String sp = " ";

        while ( ! line.equals( "END" )){

            nGaps = numGaps(line);

            if (nGaps == 0) { line = compLine(line, width).replace(" ", "."); }
            else if (nGaps == width) { line = line.replace(" ", "."); }

            else{
                int posArray[] = new int[nGaps];
                posArray = pos(line, nGaps);
                gapsLeft = width - line.length();
                spToAdd = gapsLeft / nGaps;
                modLeft = gapsLeft % nGaps;
                route = gapsLeft / nGaps;
                sp = spGen(spToAdd);

                line = reFormat(posArray, line, width, sp, spToAdd);
                if (line.length() < width){
                    System.out.print("#OK\n");
                    nGaps = numGaps(line);
                    int posArray2[] = new int[nGaps];
                    posArray2 = pos(line, nGaps);
                    line = compFormat(posArray2, line, modLeft);
                }
                line = line.replace(" ", ".");
            }
            System.out.println(line);
            System.out.println("#Length is: " + line.length());
            System.out.print("#Enter line of text : " );
            line = BIO.getString().trim();
        }
    }
    public static int numGaps(String oLine){
        int numGaps = 0;
        for (char c : oLine.toCharArray()) { if (c == ' ') { numGaps++; } }
        return numGaps;
    }
    public static String spGen(int count) {
        return new String(new char[count]).replace("\0", " ");
    }
    public static String compLine(String oLine, int width){
        String newLine = oLine;
        int pos = oLine.length();
        int numOSpace = width - oLine.length();
        String sp = spGen(numOSpace);
        newLine = new StringBuilder(newLine).insert(pos, sp).toString();
        return newLine;
    }
    public static int[] pos(String oLine, int nGaps){
        int posArray[] = new int[nGaps];
        int i = 0;
        for (int pos = 0; pos < oLine.length(); pos++) {
            if (oLine.charAt(pos) == ' ') { posArray[i] = pos; i++; }
        }
        //for (int y = 0; y < x; ++y) { System.out.println(posArray[y]); }
        return posArray;
    }
    public static String reFormat(int[] posArray, String oLine, int width, String sp, int spToAdd){
        String newLine = oLine;
        int mark = 0;
        for (int i = 0; i < posArray.length; ++i){ /*insert string at mark, shift next element by the num of elements inserted*/
            if (newLine.length() > width) { System.out.println("Maths is wrong: ERROR"); System.exit(1);}
            else { newLine = new StringBuilder(newLine).insert(posArray[i]+mark, sp).toString(); mark += spToAdd; }
        }
        return newLine;
    }
    public static String compFormat(int[] posArray2, String mLine, int modLeft){
        String newLine = mLine;
        int mark = 0;
        for (int i = 0; i < modLeft; ++i){
            //positions
            //if position y is != y+1 insert sp modLeft times
            if (posArray2[i] != posArray2[i+1] && posArray2[i] != posArray2[posArray2.length - 1]){
                newLine = new StringBuilder(newLine).insert(posArray2[i]+mark, " ").toString(); mark++;
            }
        }
        return newLine;
    }
}

【讨论】:

    猜你喜欢
    • 2014-09-04
    • 1970-01-01
    • 2016-10-19
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    相关资源
    最近更新 更多