-1

How can I add 0 in front of every single digit number? I mean 1 to 01 etc. I have tried to add ifs like

if(c >='A' && c<= 'I')
    str = "0"+str;

but it just adds 0 in front of everything like abcd converts to 00001234 not 01020304.

This is my code.

    String A[] = new String[size];
    for (int i = 0; i < size; i++) {
        A[i] = jList1.getModel().getElementAt(i);
        String[] Text = A[i].split("");
        String s = jList1.getModel().getElementAt(i);
        String str = ("");
        for (int z = 0; z < Text.length; z++) {
            for (int y = 0; y < Text[z].length(); y = y + 1) {
                char c = s.charAt(z);
                if (c >= 'A' && c <= 'Z') {
                    str += c - 'A' + 1;

                } else if (c >= 'a' && c <= 'z') {
                    str += c - 'a' + 1;

                } else {
                    str += c;
                }
            }
            str = str + "";
        }
    }
user1803551
  • 12,965
  • 5
  • 47
  • 74
Tryout.
  • 1
  • 2

5 Answers5

1

This Worked for me

public String addZero(int number)
{
    return number<=9?"0"+number:String.valueOf(number);
}``
Sarath SVS
  • 49
  • 1
  • 8
0
    String str = "abcd-zzz-AAA";

    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < str.length(); i++) {
        char ch = str.toLowerCase().charAt(i);
        if (ch >= 'a' && ch <= 'z') {
            sb.append('0');
            sb.append(ch - 'a' + 1);
        } else {
            sb.append(ch);
        }
    }

Result: abcd-zzz-AAA -> 01020304-026026026-010101

Final fix :-)

Bor Laze
  • 2,458
  • 12
  • 20
0

One way to do this would be to use a StringJoiner with Java 8:

String s = "abcdABCD";

s = s.chars()
     .mapToObj(i -> Integer.toString((i >= 'a' && i <= 'z' ? i - 'a' : i - 'A') + 1))
     .collect(Collectors.joining("0", "0", "")));

System.out.println(s);

>> 0102030401020304
Jacob G.
  • 28,856
  • 5
  • 62
  • 116
0

use String#chars to get a stream of its characters, then for each one do the manipulation you want.

public class Example {

    public static void main(String[] args) {
        String s = "aBcd1xYz";
        s.chars().forEach(c -> {
            if (c >= 'a' && c <= 'z')
                System.out.print("0" + (c - 'a' + 1));
            else if (c >= 'A' && c <= 'Z')
                System.out.print("0" + (c - 'A' + 1));
            else
                System.out.print(c);
        });
    }
}

Ouput:

0102030449024025026

user1803551
  • 12,965
  • 5
  • 47
  • 74
-1

You can add zero in front of single digit number using String.format.

System.out.println(String.format("%02d",1));
System.out.println(String.format("%02d",999));

The first line will print 01, second line prints 999 no zero padding on the left.

Padding zero with length of 2 and d represents integer.

I hope this helps.