-3

Say I have a string x and I want to add some character x amount of times so that string x becomes of length y, how would I do this?

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;

Another example:

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

I want to avoid using StringBuilder to append characters.

My thought process:

  1. Create a Char array of length y.
  2. Copy the string to array.
  3. Attempt to shift the characters one by one from the furthest character to the right.
Amir
  • 10,600
  • 9
  • 48
  • 75
  • 1
    Why `"this is a line"` and not `"this is a line"`? (Ahh whitespace removal!) What is your logic? What did you attempt before posting your question? – Sotirios Delimanolis Jan 08 '16 at 23:20
  • 1
    `StringBuilder`; build a `char[]`; `String#substring` – MadProgrammer Jan 08 '16 at 23:20
  • @ Sotiris I'm afraid I don't understand your question. I attempted to find occurrences of white-spaces and then append white-spaces to the already existing white-space. But I am not sure how to do this. – Bernardo Pliego-Garcia Jan 08 '16 at 23:23
  • 2
    The comments here remove whitepsace, so that wasn't formatted correctly. I'm asking how do you decide where the whitespace should go? Evenly? Towards the front, the back? What is the logic of your algorithm? Have you tried implementing it? – Sotirios Delimanolis Jan 08 '16 at 23:24
  • @ redFIVE Like the center function on a word processor – Bernardo Pliego-Garcia Jan 08 '16 at 23:25
  • @Sotiris Sorry, deciding that the whitespace should be inserted between the words, evenly from left to right until the string is of a certain length. I will reformat it, sec. – Bernardo Pliego-Garcia Jan 08 '16 at 23:27
  • @MadProgrammer is there any way to di it without using StringBuilder? – Bernardo Pliego-Garcia Jan 08 '16 at 23:31
  • 1
    What if your string is `a____b_c` (length 8)? Should it be balanced to `a___b___c` if desired length is 9 (notice that earlier between `a` and `b` ware 4 spaces and now are 3)? – Pshemo Jan 08 '16 at 23:36
  • @BernardoPliego-Garcia Will something like `x = x.replace("_", "___")` work for you? You may need to do some math to determine how many you should replace the original with, but that shouldn't be too difficult. – Taelsin Jan 08 '16 at 23:37
  • @Pshemo Yes, balanced to a___b___c – Bernardo Pliego-Garcia Jan 08 '16 at 23:39
  • @BernardoPliego-Garcia what about `a____b_c` (length 8) and now desired length 10 should it be `a____b___c`? (4 spaces, then 3)? – Frakcool Jan 08 '16 at 23:41
  • "Yes, balanced to a___b___c" then you should put that in your question then. Don't make potential answerers read every comment to see this requirement. – Pshemo Jan 08 '16 at 23:42
  • @Frakcool yes 4 spaces, then 3 – Bernardo Pliego-Garcia Jan 08 '16 at 23:42
  • @Taelsin it will not work because replace(o, n) needs to be flexible; is there any way to vary the second parameter? e.g. x = x.replace("_", "_"*5)? – Bernardo Pliego-Garcia Jan 08 '16 at 23:50
  • @BernardoPliego-Garcia A quick google search turned [this](http://stackoverflow.com/questions/1235179/simple-way-to-repeat-a-string-in-java) up. It should do the trick. – Taelsin Jan 08 '16 at 23:59
  • @BernardoPliego-Garcia Indirectly, yes, but it's likely that most solutions will be compiled down to use `StringBuilder` internally anyway – MadProgrammer Jan 09 '16 at 00:39
  • 1
    Why do you want to avoid using StringBuilder? One solution would be to copy the source code for StringBuilder into another file, save as MyStringBuilder, make necessary modifications to make sure it compiles, and use MyStringBuilder. – djechlin Jan 09 '16 at 01:27

3 Answers3

1

I hope I understood you correctly but I think this code does what you're requesting.

Edit: this one will distribute the specified character evenly and can create strings like "a__b_c" if the string isn't long enough yet.

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());
}
}

Old solution:

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);
}

}
The Coding Wombat
  • 805
  • 1
  • 10
  • 29
  • It doesn't work with `a____b_c` (length 8) as of OP's [comment](http://stackoverflow.com/questions/34687687/most-basic-way-to-insert-a-character-into-a-string-in-java?noredirect=1#comment57122393_34687687) it should be `a___b___c` with a length of 9. And with a length of 10 it should be `a____b___c` (4 spaces, then 3) – Frakcool Jan 09 '16 at 00:50
  • I'm sorry for that, OP could have been a bit clearer though. And I think this example might enable him to do exactly what he wants himself. I might try and fix it myself later. – The Coding Wombat Jan 09 '16 at 00:51
1

I did this one because when I started doing a pseudo code it was a bit challenging for me, though I'm not a fan of answering questions like this on "gimme teh codez".

I recommend you though using StringBuilder on String concatenation inside for loops because it's more efficient than actual String concatenation with +=.

Note that:

  • This program adds spaces to the end, that's why I print it's length trimmed.
  • I split it by space with a regex \\s+ instead of _ because that's how you wrote it 1st

The following code works for

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)

Code:

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());
    }
}

Next time try to do it yourself 1st and show YOUR logic, then your question will be better received (maybe with upvotes instead of downvotes) this is called a Runnable Example. I also recommend you to take a look at String concatenation vs StringBuilder and How to ask a good question, also you might want to Take the tour

Community
  • 1
  • 1
Frakcool
  • 10,915
  • 9
  • 50
  • 89
0

Here is my solution:

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;
    }
}