SoFunction
Updated on 2025-05-17

How to use multiplication signs to repeat strings

Java multiplication to repeat string function

If you want to achieve string duplication in Java, you can use the following methods:

1. Utilizing cycles

String result = "";
for (int i = 0; i < 4; i++) {
    result += "FF";
}
// The result is "FFFF"

2. Use StringBuilder

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 4; i++) {
    ("FF");
}
String result = ();
// The result is "FFFF"

3. Adopt the method introduced by Java 11

String result = "FF".repeat(4);
// The result is "FFFF"

4. Use case demonstration

import ;
import ;

public class StringMultiplier {
    // Regular expression matching the "string"*number format    private static final Pattern MULTIPLY_PATTERN = ("\"([^\"]*)\"\\s*\\*\\s*(\\d+)");

    /**
      * Process input containing multiple string repeat expressions
      * For example: "FF"*4 + "0"*2 will be processed as FFFF00
      * @param input Input containing string repeat expressions
      * @return Processed string
      */
    public static String processMultipliers(String input) {
        if (input == null || ()) {
            return "";
        }

        String result = input;
        Matcher matcher = MULTIPLY_PATTERN.matcher(result);

        // Loop to process all matching string repeat expressions        while (()) {
            String str = (1);  // Capture strings in quotes            int times = ((2));  // Capture the number of repetitions
            // Build the repeated string            String repeated = (times);

            // Use and process special characters            String original = ((0));
            result = ((original), (repeated));

            // Update the Matcher to match the replaced string            matcher = MULTIPLY_PATTERN.matcher(result);
        }

        return result;
    }

    public static void main(String[] args) {
        // Example 1: Processing a single expression        (processMultipliers("\"FF\"*4"));  // Output: FFFF
        // Example 2: Handling multiple expressions and other text        (processMultipliers("A=\"FF\"*4 + \"0\"*2"));  // Output: A=FFFF00
        // Example 3: Processing strings containing special characters        (processMultipliers("\"*.*\"*3"));  // Output: *.**.**.**    }
}

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.