settingsAccountsettings
Menusettings

Q: String Length - Java Task (StringBuilder)

+13 votes

Write a program that reads from the console a string of maximum 20 characters. If the length of the string is less than 20, the rest of the characters should be filled with *.

Print the resulting string on the console.

Examples:

Input:

Welcome to SoftUni!

a regular expression (abbreviated regex or regexp and sometimes

called a rational expression)

is a sequence of characters that forms a search pattern

C#

 

Output:

Welcome to SoftUni!*

a regular expression

C#******************

 

asked in Java category by user eiorgert
edited by user golearnweb

1 Answer

+1 vote
 
Best answer

Here's the answer:

import java.util.Scanner;

public class Pr_02_StringLength {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] input = scanner.nextLine().split("");
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < input.length; i++) {
            sb.append(input[i]);
        }

        for (int i = 0; i < 20; i++) {
            sb.append("*");
        }

        sb.setLength(20);

        System.out.println(sb);
    }
}

 

answered by user hues
selected by user golearnweb
...