How to pad a String in Java10 Sept 2024 | 4 min read Padding a string in Java refers to the practice of appending specific characters, typically spaces or a chosen character, to the start, end, or both sides of a string. The technique is employed to reach a specified length or to align text uniformly. It's a technique frequently used in multiple contexts, including organizing text in tabular formats, aligning content in documents or reports, or improving the overall appearance of textual output. Example 1: Input: String str1 = "Java"; char ch1 = '-'; int L1 = 10; Output: Left Padding: "------Java" Center Padding: "---Java----" Right Padding: "Java------" Example 2: Input: String str2 = "123"; char ch2 = '*'; int L2 = 8; Output: Left Padding: "*****123" Center Padding: "**123***" Right Padding: "123*****" Approach: Using String format() methodThe String.format() method in Java returns a formatted string using the given locale, specified format string, and arguments. The method allows for creating strings with placeholders replaced by formatted values. Syntax:
Algorithm:Step 1: Set the original string (originalString) to "Hello" and also define the desired length for padding (desiredLength) as 10. Step 2: Call the padRight method with the original string, desired length, and the padding character '_' to get the right-padded string. Step 3: Call the padLeft method with the original string, desired length, and the padding character '_' to get the left-padded string. Step 4: Create a right-padded string by left-justifying `input` with `String.format`, replacing spaces with `paddingChar`, and returning it. Step 5: Left-pad `input` by right-justifying it using `String.format`, replacing spaces with `paddingChar`, and returning the result. Implementation:Filename: StringPaddingExample.java Output: Padded Right: 'Hello_____' Padded Left: '_____Hello' Approach: Using Apache Common LangApache Commons Lang's StringUtils class provides convenient methods such as leftPad(), center(), and rightPad() for easily padding strings on the left, center, and right, respectively. These methods are valuable for aligning text within a specified length by adding padding characters. The functionality is commonly used in scenarios like formatting output, designing user interfaces, and aligning data in reports. The simplicity and effectiveness of these methods contribute to improved code readability and presentation in Java applications. Algorithm:Step 1: Initialize a string originalString and an integer desiredLength. Step 2: Call padLeft with originalString, desiredLength, and a padding character, storing the result in leftPadded. Print leftPadded. Step 3: Call padCenter with originalString, desiredLength, and a padding character, storing the result in centerPadded. Print centerPadded. Step 4: Call padRight with originalString, desiredLength, and a padding character, storing the result in rightPadded. Print rightPadded. Step 5: Implement `StringUtils.leftPad` to append the specified padding character to the beginning of the input string until it reaches the desired length, then return this left-aligned string. Step 6: Utilize `StringUtils.center` to position the input string in the middle of a field with the set length, filling the space on both sides with the chosen character, and return the centrally aligned string. Step 7: Apply `StringUtils.rightPad` to add the selected padding character to the end of the input string until it attains the specified length, and return this right-aligned string. Implementation:Filename: StringUtilsExample.java Output: Left Padded: '__________Hello' Center Padded: '______Hello______' Right Padded: 'Hello____________' |
We have already discussed the factorial of a number. However, we still have to discuss the factorial of a large number separately. It is because one cannot compute the factorial of a large number with the approach that is used to compute the factorial of a...
8 min read
In programming, sorting is important because it puts elements of an array in a certain order. The widely used order is alphabetical order or natural order. The sorting is used for canonicalizing (the process of converting data in the standard form) data and for producing a...
3 min read
In this section, we will create Java programs to set matrix elements to zero with different logics. It is the most important problem usually asked in coding round interviews. Given a m*n matrix. If any element of the matrix is 0, set it's entire row and column...
13 min read
Efficiently computing the sums of the primary and secondary diagonals of a matrix involves leveraging index properties to minimize iterations. Instead of using nested loops to traverse the entire matrix, a single loop can directly access diagonal elements, improving performance and simplifying the code. This approach...
6 min read
Problem Statement You are given a mathematical sequence with the following terms: 2, 12, 36, 80, 150, … The objective is to determine the n-th term of this sequence by deriving its mathematical formula, implementing it programmatically, and verifying its correctness. Overview Analyze the sequence...
4 min read
The use of recursion to reverse a doubly linked list in Java requires an understanding of both the structure of a doubly linked list and the recursion process. A doubly linked list's nodes are composed of three components: a data field, a pointer to the node...
5 min read
The matrix exponential is a fundamental concept in linear algebra, with applications spanning quantum mechanics, control theory, and differential equations. It generalizes the scalar exponential function (e^x) to matrices. For a square matrix (A), its exponential, denoted as (e^A ), is defined by the infinite series: ...
7 min read
The compound assignment operator is the combination of more than one operator. It includes an assignment operator and an arithmetic operator or a bitwise operator. The specified operation is performed between the right operand and the left operand, and the resultant is assigned to the left...
7 min read
Two strings S1 and S2 are given to us. Our task is to find substring str such that S2 is a subsequence of str. If there are multiple valid substrings, then the substrings of the minimum size should be taken into consideration. If multiples valid substrings...
4 min read
The is a primitive data type. It is used to declare variables. It can also be used with methods to return integer type values. It can hold a 32-bit signed two's complement integer. Points to remember The int contains minimum value of -231 and a maximum...
2 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India