Grant Lee
Grant Lee

Reputation: 77

Take in String that contains number characters and add commas to each thousands place WITHOUT converting string into int or long

I want to take in a string for example "1234567890" and add commas to each thousands place in the number. However, I don't want to parse this string into an int or long. I think I might need to use recursion but I dont know how.

String number1 = "1234567890";
System.out.println(stringNumberAddCommas(number1));
//output == 1,234,567,890

public static String stringNumberAddCommas(String number1){  }

Upvotes: 0

Views: 118

Answers (4)

Zachary
Zachary

Reputation: 323

I'd define an offset to find the length of the first substring, then iterate over the string in 3 character substrings.

StringJoiner would also be helpful in adding the needed commas.

public static String stringNumberAddCommas(String str){
    int offset = str.length() % 3 != 0 ? str.length() % 3 : 3;
    StringJoiner sj = new StringJoiner(",");
    for (int s = 0, i = offset; i <= str.length(); s = i, i += 3) {
        sj.add(str.substring(s, i));
    }
    return sj.toString();
}

Upvotes: 1

sanjeevjha
sanjeevjha

Reputation: 1549

we can achieve this as below as well-

    public static String stringNumberAddCommas(String number) {
    for (int i = number.length() - 1; i >= 0; ) {
        if (i >= 3) {
            number = number.substring(0, i - 2) + "," + number.substring(i - 2);
        }
        i = i - 3;
    }
    System.out.println("number=" + number);
    return number;
}

Upvotes: 1

Deepanshu Rathi
Deepanshu Rathi

Reputation: 411

    String test = "1234567890";
    String reversed = new StringBuffer(test).reverse().toString();
    int i = 0;
    StringBuilder ans = new StringBuilder();
    while(i+3<reversed.length()){
        ans.append(reversed, i, i + 3).append(",");
        i+=3;
    }
    ans.append(reversed, i, reversed.length());
    String solution = ans.reverse().toString();

Upvotes: 1

rzwitserloot
rzwitserloot

Reputation: 103913

There's no need to mess with recursion; all you need is to realize that you need to either work backwards or do some very basic math based on length.

Given a pile o digits that is, say, 8 characters long, that's all the information you need to know that the first comma is after 2 digits, and then every further comma at +3 digits from that position until you reach the end.

Tools needed:

  • "12345678".length() (= 8)
  • "12345678".substring(2, 5) (= "345")
  • a for (int i = ...; i < in.length(); i+= 3) loop.
  • a new StringBuilder() along with its .append() method, both for appending the comma as well as those substrings.
  • Some exceedingly basic math on that length, involving in particular the % operator. a % b divides a by b, tosses the result in the garbage, and returns the leftovers. In other words, 5 % 3 returns 2 (because 5 divides into 3 one time, and that leaves a remainder of 2).

Upvotes: 1

Related Questions