How to center a string by formatting in Java? - java

I want my String to be formatted both from the left and right side, so it always keeps standing in the center.
Let's say I want the total length to be 30 symbols (let's mark spaces as stars to see clearly). I want the following result.
sampleString -> *********sampleString*********
sampleLongLongString -> *****sampleLongLongString*****
I tried to do the following.
result = padLeft("", 15) + padRight(myString, 15);
or
result = padLeft(padRight(myString, 15), 15);
For functions,
public static String padRight(String s, int n) {
return String.format("%1$-" + n + "s", s);
}
public static String padLeft(String s, int n) {
return String.format("%1$" + n + "s", s);
}
but no result.

You can create a method to add padding based on the length of the String.
Basically, you have to decide the total/max(left+right) padding for all the Strings. Please take a look at following method.
It also manages the space inside the String. Method will just return actual String if padding can not be added according to maxPadding.
public static String getPaddedString(String str, char paddingChar) {
if (str == null) {
throw new NullPointerException("Can not add padding in null String!");
}
int maxPadding = 20;//This is what you have to decide
int length = str.length();
int padding = (maxPadding - length) / 2;//decide left and right padding
if (padding <= 0) {
return str;// return actual String if padding is less than or equal to 0
}
String empty = "", hash = "#";//hash is used as a place holder
// extra character in case of String with even length
int extra = (length % 2 == 0) ? 1 : 0;
String leftPadding = "%" + padding + "s";
String rightPadding = "%" + (padding - extra) + "s";
String strFormat = leftPadding + "%s" + rightPadding;
String formattedString = String.format(strFormat, empty, hash, empty);
//Replace space with * and hash with provided String
String paddedString = formattedString.replace(' ', paddingChar).replace(hash, str);
return paddedString;
}
Following program proves that above method works,
public class Test {
public static void main(String args[]) {
System.out.println(getPaddedString("Hello", '*'));
System.out.println(getPaddedString("Hi23", '#'));
System.out.println(getPaddedString("Test. .Test", '%'));
System.out.println(getPaddedString(
"By the way, It's to long to fix !!", '*'));
}
}
OUTPUT
************Hello************
#############Hi23############
%%%%%%%%%Test. .Test%%%%%%%%%
By the way, It's to long to fix !!

Here's an easy-to-understand method to do it:
public static String center(String string, int length, char pad) {
StringBuilder sb = new StringBuilder(length);
sb.setLength((length - string.length()) / 2);
sb.append(string);
sb.setLength(length);
return sb.toString().replace('\0', pad);
}
With this code, when the total padding required is odd, the right-side padding has one extra pad char. To change the behaviour so that the left side gets the extra pad, change line 2 to:
sb.setLength((length - string.length() + 1) / 2);

This method will do the trick.
/**
* #param int w : length of the formatted string (e.g. 30)
* #param String s : the string to be formatted
* #param char c : character to pad with
* #param boolean pr: If s is odd, pad one extra left or right
* #return the original string, with pad 'p' on both sides
*/
private String pad(String s, int w, char c, boolean pr){
int pad = w-s.length();
String p = "";
for (int i=0; i<pad/2; i++)
p = p + c;
/* If s.length is odd */
if (pad%2 == 1)
/* Pad one extra either right or left */
if (pr) s = s + c;
else s = c + s;
return (p+s+p)
}

Related

Trying to alternate two strings together in Java

/* Programs goal is to take two strings and use a method to alternate the characters.
example - "test" "case" -> "tceasste"
Sorry I tried looking at other similar questions but I didn't understand how they worked as I am very new to Java and coding in general.
*/
public class MyProgram extends ConsoleProgram
{
public void run()
{
System.out.println(sCombine("test","case")); //"tceasste"
System.out.println(sCombine("avalanche","dog")); //"advoaglanche"
System.out.println(sCombine("","water")); //"water"
}
public String sCombine(String a, String b)
{
String result = "";
int lengtha = a.length();
int lengthb = b.length();
int lengthc = 0;
if(lengtha < lengthb)
{
lengthc = lengtha;
}
else
{
lengthc = lengthb;
}
for(int i = 0; i < lengthc; i++)
{
char currentA = a.charAt(i);
char currentB = b.charAt(i);
result += a;
result += b;
}
return result;
}
}
The problem is that you're doing:
result += a;
You need to do:
result += currentA;
I would also suggest looking at the StringBuilder class. It has a lot of built in functionality for things of this nature :)
Just another way. Read all the comments in code:
/**
* Sequentially blends two strings together one character at a time, for
* example, if the first argument was "cat" and the second argument was
* "dog" then the returned result will be: "cdaotg".<br><br>
*
* <b>Example Usage:</b><pre>
* {#code
* final String a = "cat";
* final String b = "elephant";
* String newString = sCombine(a, b);
* System.out.println(newString);
* // Console will display: cealte }
*
* OR
* {#code
* final String a = "cat";
* final String b = "elephant";
* String newString = sCombine(a, b, true); // true is optionally supplied here.
* System.out.println(newString);
* // Console will display: eclaetphant }</pre>
*
* #param stringA (String) The first String to blend.<br>
*
* #param stringB (String) The second String to blend.<br>
*
* #param startWithLongest (Optional - boolean varArgs) Default is false <pre>
* whereas this method will always take the first
* supplied argument and blend the second argument
* into it. In this default situation, the first
* argument is always considered to contain the
* longest String. If however, the second argument
* contains more characters then the those extra
* characters will be truncated, for example: "cat"
* and "elephant". Result will be: "cealte". It would
* be beneficial to always pass the longest string as
* the first argument in order to achieve the result
* of: "eclaetphant".
*
* If boolean true is supplied to this optional parameter
* then the longest argument passed to this method will
* always be considered as the first argument rather than
* the first supplied argument, for example: "cat" as the
* first argument and "elephant" as the second argument
* and true as the third argument will return a result
* of "eclaetphant".
*
* Supplying nothing forces default to be used.</pre>
*
* #return (String) The blended String;
*/
public static String sCombine(final String stringA, final String stringB,
final boolean... startWithLongest) {
String strgA = stringA, strgB = stringB; // So to maintain original Strings
/* If `true` is supplied to the startWithLongest optional
vararg parameter then ensure the String argument with the
most characters is the first argument (if true, always place
the longest first). */
if (startWithLongest.length > 0 && startWithLongest[0]) {
if (strgB.length() > strgA.length()) {
strgA = stringB;
strgB = stringA;
}
}
// Build the new blended string
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < strgA.length(); i++) {
sb.append(strgA.charAt(i))
/* 'Ternary Operator' is used here to ensure strgB
contains the current index to carry on. If not
then just the remaining characters of strgA are
sequentially apended to the StringBuilder object
to finish up things. */
.append(i < strgB.length() ? strgB.charAt(i) : "");
}
return sb.toString();
}
You can use a loop that iterates the maximum length of both the strings. Then you can extract the individual character at the ith position and add it alternatively to a resulting String object. I have used StringBuiler as it mutable( diff here ) This is the code that I have attached.
public class MyProgram {
public static void main(String[] args) {
System.out.println(sCombine("test", "case")); // "tceasste"
System.out.println(sCombine("avalanche", "dog")); // "advoaglanche"
System.out.println(sCombine("", "water")); // "water"
}
public static String sCombine(String a, String b) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < Math.max(a.length(), b.length()); i++) {
char aChar = i < a.length() ? a.charAt(i) : '#';
char bChar = i < b.length() ? b.charAt(i) : '#';
if (aChar != '#') {
result.append(aChar + "");
}
if (bChar != '#') {
result.append(bChar + "");
}
}
return result.toString();
}
}
and the output is :
tceasste
advoaglanche
water
You can use substring to savely append the remainder of the Strings. Should the limit be out of bounds, no exception will be thrown, because substring will just return an empty String.
public String sCombine(String a, String b) {
final StringBuilder builder = new StringBuilder();
final int min = Math.min(a.length(), b.length());
for (int i = 0; i < min; i++) {
builder.append(a.charAt(i)).append(b.charAt(i));
}
builder.append(a.substring(min)).append(b.substring(min));
return builder.toString();
}
take two strings and use a method to alternate the characters.
example - "test" "case" -> "tceasste"
private static String mixedUp(String first, String second)
{
First, identify the shorter string so it won't attempt to pull a character that is out out bounds
int length = (first.length() > second.length())
? second.length() : first.length();
Then for that length, add their alternating characters to a new String() Object like so:
String output = new String();
for(int index = 0; index < length; index++)
{
output += first.charAt(index);
output += second.charAt(index);
}
You can use substring to savely append the remainder of the Strings. Should the limit be out of bounds, no exception will be thrown, because substring will just return an empty String. - #thinkgruen
You can add the rest of the characters using the ternary operator again like so:
output += (first.length() > second.length())
? second.substring(length) : first.substring(length);
return output;
}

Need to encode repetitive pattern in String with * , such that * means "repeat from beginning"

Encoding format: introduce * to indicate "repeat from beginning". Example. Input-{a,b,a,b,c,a,b,a,b,c,d} can be written as {a , b, * ,c, * , d}. Output:5; E.g 2: ABCABCE, output- 5.
Here * means repeat from beginning. For example if given String is ABCABCABCABC , it will return ABC**, another example is if String is ABCABCABC, it will return ABC*ABC.
I have the below code but this code assumes that the string will contain the repetitive pattern only and no other characters, I want to modify it to check :
1. Which pattern is repeating
2. Ignore non repeating patterns
2. encode that pattern according to the problem statement
import java.util.Scanner;
public class Magicpotion {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string:");
String str = sc.nextLine();
int len = str.length();
if (len != 0) {
int lenby3 = len / 3;
int starcount = ( int).(Math.log(lenby3) / Math.log(2));
int leftstring = (lenby3 - (int) Math.pow(2, starcount));
int resultlen = (1 * 3) + starcount + (leftstring * 3);
System.out.println("ResultLength: " + resultlen);
System.out.print("ABC");
for (int i = 0; i < starcount; i++) {
System.out.print("*");
}
for (int i = 0; i < leftstring; i++) {
System.out.print("ABC");
}
} else
System.out.println("ResultLength: " + 0);
}
}
Here my assumption is that ABC will always be repeating pattern , hence I have divided the length by 3. I want to generalise it such that I find the repeating pattern which can be a AB or BC or ABCD and proceed accordingly.
This looks like homework. So instead of a full solution just some hints:
You can process the input string character by character and encode as you go. If you have at some point already read k characters and the next k characters are exactly the same, output a * and advance to position 2k.
Otherwise, output the next input character and advance position to k+1.
As mentioned by dyukha this algorithm does not always result in the shortest possible encoding. If this is required some more effort has to be put into the search.
This problem can be solved using dynamic programming.
Assume that you processed your stay at some position i. You want to understand what it the minimal length of encoding of str[0..i]. Let's call it ans[i]. You have two options:
Just add i-th character to the encoding. So the length is ans[i-1] + 1.
You may write *, when possible. In this case the length is ans[i / 2] + 1 or something like this.
The final length is in ans[n-1]. You can store how you obtained ans[i] to recover the encoding itself.
Checking whether you can write * can be optimized, using some hashing (to obtain O(n) solution instead of O(n^2)).
The difference with Henry's solution is that he always applies * when it's possible. It's not clear to me that it results into the minimal length (if I understood correctly, aaaaaa is a counterexample), so I'm giving a solution I'm sure about.
/**
* #author mohamed ali
* https://www.linkedin.com/in/oo0shaheen0oo/
*/
public class Magic_potion_encoding
{
private static int minimalSteps( String ingredients )
{
StringBuilder sb = new StringBuilder(ingredients);
for(int i =0;i<sb.length();i++)
{
char startChar = sb.charAt(i);
int walkingIndex1=i;
int startIndex2 =sb.toString().indexOf(startChar,i+1);
int walkingIndex2=startIndex2;
while(walkingIndex2 !=-1 && walkingIndex2<sb.length() && sb.charAt(walkingIndex1) == sb.charAt(walkingIndex2) )
{
if(walkingIndex1+1==startIndex2)
{
String subStringToBeEncoded = sb.substring(i,walkingIndex2+1);//substring the string found and the original "substring does not include the last index hence the +1
int matchStartIndex = sb.indexOf(subStringToBeEncoded,walkingIndex2+1);// look for first match for the whole string matched
int matchEndeIndex= matchStartIndex+subStringToBeEncoded.length();
int origStartIndex=i;
int origEndIndex = i+subStringToBeEncoded.length();
if (matchStartIndex!=-1 )
{
if(origEndIndex==matchStartIndex)
{
sb.replace(matchStartIndex,matchEndeIndex,"*");
}
else
{
while(matchStartIndex!=-1 && matchEndeIndex<sb.length() && sb.charAt(origEndIndex) == sb.charAt(matchEndeIndex) )
{
if(origEndIndex==matchStartIndex-1)// if the index of the 2 strings are right behind one another
{
sb.replace(matchStartIndex,matchEndeIndex+1,"*");
}
else
{
origEndIndex++;
matchEndeIndex++;
}
}
}
}
sb.replace(startIndex2,walkingIndex2+1,"*");
break;
}
walkingIndex1++;
walkingIndex2++;
}
}
System.out.println("orig= " + ingredients + " encoded = " + sb);
return sb.length();
}
public static void main( String[] args )
{
if ( minimalSteps("ABCABCE") == 5 &&
minimalSteps("ABCABCEA") == 6 &&
minimalSteps("abbbbabbbb") == 5 &&
minimalSteps("abcde") == 5 &&
minimalSteps("abcbcbcbcd") == 6 &&
minimalSteps("ababcababce") == 6 &&
minimalSteps("ababababxx") == 6 &&
minimalSteps("aabbccbbccaabbccbbcc") == 8)
{
System.out.println( "Pass" );
}
else
{
System.out.println( "Fail" );
}
}
}
Given that the repetitions are from the beginning, every such repeating substring will have the very first character of the given string. [Every repetition needs to be represented by a "star". (i.e ABCABCABC ans = ABC** ) . If all sequential repetitions are to be represented with one "star". (i.e ABCABCABC and = ABC* ), a slight modification to (2) will do the thing (i.e remove the if case where the just a star is added)]
Divide the given string to substrings based on the first character.
Eg. Given String = "ABABCABD"
Sub Strings = {"AB", "ABC", "AB", "ABD"}
Just traverse through the list of substrings and get the required result. I've used a map here, to make the search easy.
Just a rough write up.
SS = {"AB", "ABC", "AB", "ABD"};
result = SS[0];
Map<string, bool> map;
map.put(SS[0],true);
for (i = 1; i < SS.length; i++){
if (map.hasKey(SS[i])){
result += "*";
}
else {
res = nonRepeatingPart(SS[i], map);
result += "*" + res;
map.put(SS[i], true);
}
}
String nonRepeatingPart(str, map){
for (j = str.length-1; j >= 0; j--){
if (map.hasKey(str.subString(0, j))){
return str.subString(j, str.length-1);
}
}
return throwException("Wrong Input");
}
string getCompressed(string str){
string res;
res += str[0];
int i=1;
while(i<str.size()){
//check if current char is the first char in res
char curr = str[i];
if(res[0]==curr){
if(str.substr(0,i)==str.substr(i,i)){
res += '*';
i+=i; continue;
}else{
res += curr;
i++; continue;
}
}else {
res += curr;
i++; continue;
}
}
return res;
}
int main()
{
string s = "ABCABCABC";
string res = getCompressed(s);
cout<<res.size();
return 0;
}

Generate fixed length Strings filled with whitespaces

I need to produce fixed length string to generate a character position based file. The missing characters must be filled with space character.
As an example, the field CITY has a fixed length of 15 characters. For the inputs "Chicago" and "Rio de Janeiro" the outputs are
" Chicago"
" Rio de Janeiro".
Since Java 1.5 we can use the method java.lang.String.format(String, Object...) and use printf like format.
The format string "%1$15s" do the job. Where 1$ indicates the argument index, s indicates that the argument is a String and 15 represents the minimal width of the String.
Putting it all together: "%1$15s".
For a general method we have:
public static String fixedLengthString(String string, int length) {
return String.format("%1$"+length+ "s", string);
}
Maybe someone can suggest another format string to fill the empty spaces with an specific character?
Utilize String.format's padding with spaces and replace them with the desired char.
String toPad = "Apple";
String padded = String.format("%8s", toPad).replace(' ', '0');
System.out.println(padded);
Prints 000Apple.
Update more performant version (since it does not rely on String.format), that has no problem with spaces (thx to Rafael Borja for the hint).
int width = 10;
char fill = '0';
String toPad = "New York";
String padded = new String(new char[width - toPad.length()]).replace('\0', fill) + toPad;
System.out.println(padded);
Prints 00New York.
But a check needs to be added to prevent the attempt of creating a char array with negative length.
This code will have exactly the given amount of characters; filled with spaces or truncated on the right side:
private String leftpad(String text, int length) {
return String.format("%" + length + "." + length + "s", text);
}
private String rightpad(String text, int length) {
return String.format("%-" + length + "." + length + "s", text);
}
For right pad you need String.format("%0$-15s", str)
i.e. - sign will "right" pad and no - sign will "left" pad
See my example:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("================================");
for(int i=0;i<3;i++)
{
String s1=sc.nextLine();
Scanner line = new Scanner( s1);
line=line.useDelimiter(" ");
String language = line.next();
int mark = line.nextInt();;
System.out.printf("%s%03d\n",String.format("%0$-15s", language),mark);
}
System.out.println("================================");
}
}
The input must be a string and a number
example input : Google 1
String.format("%15s",s) // pads left
String.format("%-15s",s) // pads right
Great summary here
import org.apache.commons.lang3.StringUtils;
String stringToPad = "10";
int maxPadLength = 10;
String paddingCharacter = " ";
StringUtils.leftPad(stringToPad, maxPadLength, paddingCharacter)
Way better than Guava imo. Never seen a single enterprise Java project that uses Guava but Apache String Utils is incredibly common.
You can also write a simple method like below
public static String padString(String str, int leng) {
for (int i = str.length(); i <= leng; i++)
str += " ";
return str;
}
The Guava Library has Strings.padStart that does exactly what you want, along with many other useful utilities.
Here's a neat trick:
// E.g pad("sss","00000000"); should deliver "00000sss".
public static String pad(String string, String pad) {
/*
* Add the pad to the left of string then take as many characters from the right
* that is the same length as the pad.
* This would normally mean starting my substring at
* pad.length() + string.length() - pad.length() but obviously the pad.length()'s
* cancel.
*
* 00000000sss
* ^ ----- Cut before this character - pos = 8 + 3 - 8 = 3
*/
return (pad + string).substring(string.length());
}
public static void main(String[] args) throws InterruptedException {
try {
System.out.println("Pad 'Hello' with ' ' produces: '"+pad("Hello"," ")+"'");
// Prints: Pad 'Hello' with ' ' produces: ' Hello'
} catch (Exception e) {
e.printStackTrace();
}
}
Here is the code with tests cases ;) :
#Test
public void testNullStringShouldReturnStringWithSpaces() throws Exception {
String fixedString = writeAtFixedLength(null, 5);
assertEquals(fixedString, " ");
}
#Test
public void testEmptyStringReturnStringWithSpaces() throws Exception {
String fixedString = writeAtFixedLength("", 5);
assertEquals(fixedString, " ");
}
#Test
public void testShortString_ReturnSameStringPlusSpaces() throws Exception {
String fixedString = writeAtFixedLength("aa", 5);
assertEquals(fixedString, "aa ");
}
#Test
public void testLongStringShouldBeCut() throws Exception {
String fixedString = writeAtFixedLength("aaaaaaaaaa", 5);
assertEquals(fixedString, "aaaaa");
}
private String writeAtFixedLength(String pString, int lenght) {
if (pString != null && !pString.isEmpty()){
return getStringAtFixedLength(pString, lenght);
}else{
return completeWithWhiteSpaces("", lenght);
}
}
private String getStringAtFixedLength(String pString, int lenght) {
if(lenght < pString.length()){
return pString.substring(0, lenght);
}else{
return completeWithWhiteSpaces(pString, lenght - pString.length());
}
}
private String completeWithWhiteSpaces(String pString, int lenght) {
for (int i=0; i<lenght; i++)
pString += " ";
return pString;
}
I like TDD ;)
Apache common lang3 dependency's StringUtils exists to solve Left/Right Padding
Apache.common.lang3 provides the StringUtils class where you can use the following method to left padding with your preferred character.
StringUtils.leftPad(final String str, final int size, final char padChar);
Here, This is a static method and the parameters
str - string needs to be pad (can be null)
size - the size to pad to
padChar the character to pad with
We have additional methods in that StringUtils class as well.
rightPad
repeat
different join methods
I just add the Gradle dependency here for your reference.
implementation 'org.apache.commons:commons-lang3:3.12.0'
https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.12.0
Please see all the utils methods of this class.
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html
GUAVA Library Dependency
This is from jricher answer. The Guava Library has Strings.padStart that does exactly what you want, along with many other useful utilities.
This code works great.
String ItemNameSpacing = new String(new char[10 - masterPojos.get(i).getName().length()]).replace('\0', ' ');
printData += masterPojos.get(i).getName()+ "" + ItemNameSpacing + ": " + masterPojos.get(i).getItemQty() +" "+ masterPojos.get(i).getItemMeasure() + "\n";
Happy Coding!!
public static String padString(String word, int length) {
String newWord = word;
for(int count = word.length(); count < length; count++) {
newWord = " " + newWord;
}
return newWord;
}
This simple function works for me:
public static String leftPad(String string, int length, String pad) {
return pad.repeat(length - string.length()) + string;
}
Invocation:
String s = leftPad(myString, 10, "0");
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
int s;
String s1 = sc.next();
int x = sc.nextInt();
System.out.printf("%-15s%03d\n", s1, x);
// %-15s -->pads right,%15s-->pads left
}
}
}
Use printf() to simply format output without using any library.

Left padding a String with Zeros [duplicate]

This question already has answers here:
How can I pad a String in Java?
(32 answers)
Closed 5 years ago.
I've seen similar questions here and here.
But am not getting how to left pad a String with Zero.
input: "129018"
output: "0000129018"
The total output length should be TEN.
If your string contains numbers only, you can make it an integer and then do padding:
String.format("%010d", Integer.parseInt(mystring));
If not I would like to know how it can be done.
String paddedString = org.apache.commons.lang.StringUtils.leftPad("129018", 10, "0")
the second parameter is the desired output length
"0" is the padding char
This will pad left any string to a total width of 10 without worrying about parse errors:
String unpadded = "12345";
String padded = "##########".substring(unpadded.length()) + unpadded;
//unpadded is "12345"
//padded is "#####12345"
If you want to pad right:
String unpadded = "12345";
String padded = unpadded + "##########".substring(unpadded.length());
//unpadded is "12345"
//padded is "12345#####"
You can replace the "#" characters with whatever character you would like to pad with, repeated the amount of times that you want the total width of the string to be. E.g. if you want to add zeros to the left so that the whole string is 15 characters long:
String unpadded = "12345";
String padded = "000000000000000".substring(unpadded.length()) + unpadded;
//unpadded is "12345"
//padded is "000000000012345"
The benefit of this over khachik's answer is that this does not use Integer.parseInt, which can throw an Exception (for example, if the number you want to pad is too large like 12147483647). The disadvantage is that if what you're padding is already an int, then you'll have to convert it to a String and back, which is undesirable.
So, if you know for sure that it's an int, khachik's answer works great. If not, then this is a possible strategy.
String str = "129018";
String str2 = String.format("%10s", str).replace(' ', '0');
System.out.println(str2);
String str = "129018";
StringBuilder sb = new StringBuilder();
for (int toPrepend=10-str.length(); toPrepend>0; toPrepend--) {
sb.append('0');
}
sb.append(str);
String result = sb.toString();
You may use apache commons StringUtils
StringUtils.leftPad("129018", 10, "0");
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#leftPad(java.lang.String,%20int,%20char)
To format String use
import org.apache.commons.lang.StringUtils;
public class test {
public static void main(String[] args) {
String result = StringUtils.leftPad("wrwer", 10, "0");
System.out.println("The String : " + result);
}
}
Output : The String : 00000wrwer
Where the first argument is the string to be formatted, Second argument is the length of the desired output length and third argument is the char with which the string is to be padded.
Use the link to download the jar http://commons.apache.org/proper/commons-lang/download_lang.cgi
If you need performance and know the maximum size of the string use this:
String zeroPad = "0000000000000000";
String str0 = zeroPad.substring(str.length()) + str;
Be aware of the maximum string size. If it is bigger then the StringBuffer size, you'll get a java.lang.StringIndexOutOfBoundsException.
An old question, but I also have two methods.
For a fixed (predefined) length:
public static String fill(String text) {
if (text.length() >= 10)
return text;
else
return "0000000000".substring(text.length()) + text;
}
For a variable length:
public static String fill(String text, int size) {
StringBuilder builder = new StringBuilder(text);
while (builder.length() < size) {
builder.append('0');
}
return builder.toString();
}
I prefer this code:
public final class StrMgr {
public static String rightPad(String input, int length, String fill){
String pad = input.trim() + String.format("%"+length+"s", "").replace(" ", fill);
return pad.substring(0, length);
}
public static String leftPad(String input, int length, String fill){
String pad = String.format("%"+length+"s", "").replace(" ", fill) + input.trim();
return pad.substring(pad.length() - length, pad.length());
}
}
and then:
System.out.println(StrMgr.leftPad("hello", 20, "x"));
System.out.println(StrMgr.rightPad("hello", 20, "x"));
Use Google Guava:
Maven:
<dependency>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
<version>14.0.1</version>
</dependency>
Sample code:
Strings.padStart("129018", 10, '0') returns "0000129018"
Based on #Haroldo MacĂȘdo's answer, I created a method in my custom Utils class such as
/**
* Left padding a string with the given character
*
* #param str The string to be padded
* #param length The total fix length of the string
* #param padChar The pad character
* #return The padded string
*/
public static String padLeft(String str, int length, String padChar) {
String pad = "";
for (int i = 0; i < length; i++) {
pad += padChar;
}
return pad.substring(str.length()) + str;
}
Then call Utils.padLeft(str, 10, "0");
Here's another approach:
int pad = 4;
char[] temp = (new String(new char[pad]) + "129018").toCharArray()
Arrays.fill(temp, 0, pad, '0');
System.out.println(temp)
Here's my solution:
String s = Integer.toBinaryString(5); //Convert decimal to binary
int p = 8; //preferred length
for(int g=0,j=s.length();g<p-j;g++, s= "0" + s);
System.out.println(s);
Output: 00000101
Right padding with fix length-10:
String.format("%1$-10s", "abc")
Left padding with fix length-10:
String.format("%1$10s", "abc")
Here is a solution based on String.format that will work for strings and is suitable for variable length.
public static String PadLeft(String stringToPad, int padToLength){
String retValue = null;
if(stringToPad.length() < padToLength) {
retValue = String.format("%0" + String.valueOf(padToLength - stringToPad.length()) + "d%s",0,stringToPad);
}
else{
retValue = stringToPad;
}
return retValue;
}
public static void main(String[] args) {
System.out.println("'" + PadLeft("test", 10) + "'");
System.out.println("'" + PadLeft("test", 3) + "'");
System.out.println("'" + PadLeft("test", 4) + "'");
System.out.println("'" + PadLeft("test", 5) + "'");
}
Output:
'000000test'
'test'
'test'
'0test'
The solution by Satish is very good among the expected answers. I wanted to make it more general by adding variable n to format string instead of 10 chars.
int maxDigits = 10;
String str = "129018";
String formatString = "%"+n+"s";
String str2 = String.format(formatString, str).replace(' ', '0');
System.out.println(str2);
This will work in most situations
int number = -1;
int holdingDigits = 7;
System.out.println(String.format("%0"+ holdingDigits +"d", number));
Just asked this in an interview........
My answer below but this (mentioned above) is much nicer->
String.format("%05d", num);
My answer is:
static String leadingZeros(int num, int digitSize) {
//test for capacity being too small.
if (digitSize < String.valueOf(num).length()) {
return "Error : you number " + num + " is higher than the decimal system specified capacity of " + digitSize + " zeros.";
//test for capacity will exactly hold the number.
} else if (digitSize == String.valueOf(num).length()) {
return String.valueOf(num);
//else do something here to calculate if the digitSize will over flow the StringBuilder buffer java.lang.OutOfMemoryError
//else calculate and return string
} else {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < digitSize; i++) {
sb.append("0");
}
sb.append(String.valueOf(num));
return sb.substring(sb.length() - digitSize, sb.length());
}
}
Check my code that will work for integer and String.
Assume our first number is 129018. And we want to add zeros to that so the the length of final string will be 10. For that you can use following code
int number=129018;
int requiredLengthAfterPadding=10;
String resultString=Integer.toString(number);
int inputStringLengh=resultString.length();
int diff=requiredLengthAfterPadding-inputStringLengh;
if(inputStringLengh<requiredLengthAfterPadding)
{
resultString=new String(new char[diff]).replace("\0", "0")+number;
}
System.out.println(resultString);
I have used this:
DecimalFormat numFormat = new DecimalFormat("00000");
System.out.println("Code format: "+numFormat.format(123));
Result: 00123
I hope you find it useful!

how to split a string by position in Java

I did not find anywhere an answer.. If i have: String s = "How are you"?
How can i split this into two strings, so first string containing from 0..s.length()/2 and the 2nd string from s.length()/2+1..s.length()?
Thanks!
This should do:
String s = "How are you?";
String first = s.substring(0, s.length() / 2); // gives "How ar"
String second = s.substring(s.length() / 2); // gives "e you?"
String.substring(int i) with one argument returns the substring beginning at position i
String.substring(int i, int j) with two arguments returns the substring beginning at i and ending at j-1.
(Note that if the length of the string is odd, second will have one more character than first due to the rounding in the integer division.)
String s0 = "How are you?";
String s1 = s0.subString(0, s0.length() / 2);
String s2 = s0.subString(s0.length() / 2);
So long as s0 is not null.
EDIT
This will work for odd length strings as you are not adding 1 to either index. Surprisingly it even works on a zero length string "".
You can use 'substring(start, end)', but of course check if string isn't null before:
String first = s.substring(0, s.length() / 2);
String second = s.substring(s.length() / 2);
http://www.roseindia.net/java/beginners/SubstringExample.shtml
And are you expecting string with odd length ? in this case you must add logic to handle this case correctly.
Here's a method that splits a string into n items by length. (If the string length can not exactly be divided by n, the last item will be shorter.)
public static String[] splitInEqualParts(final String s, final int n){
if(s == null){
return null;
}
final int strlen = s.length();
if(strlen < n){
// this could be handled differently
throw new IllegalArgumentException("String too short");
}
final String[] arr = new String[n];
final int tokensize = strlen / n + (strlen % n == 0 ? 0 : 1);
for(int i = 0; i < n; i++){
arr[i] =
s.substring(i * tokensize,
Math.min((i + 1) * tokensize, strlen));
}
return arr;
}
Test code:
/**
* Didn't use Arrays.toString() because I wanted to have quotes.
*/
private static void printArray(final String[] arr){
System.out.print("[");
boolean first = true;
for(final String item : arr){
if(first) first = false;
else System.out.print(", ");
System.out.print("'" + item + "'");
}
System.out.println("]");
}
public static void main(final String[] args){
printArray(splitInEqualParts("Hound dog", 2));
printArray(splitInEqualParts("Love me tender", 3));
printArray(splitInEqualParts("Jailhouse Rock", 4));
}
Output:
['Hound', ' dog']
['Love ', 'me te', 'nder']
['Jail', 'hous', 'e Ro', 'ck']
Use String.substring(int), and String.substring(int, int) method.
int cutPos = s.length()/2;
String s1 = s.substring(0, cutPos);
String s2 = s.substring(cutPos, s.length()); //which is essentially the same as
//String s2 = s.substring(cutPos);
I did not find anywhere an answer.
The first place you should always look is at the javadocs for the class in question: in this case java.lang.String. The javadocs
can be browsed online on the Oracle website (e.g. at http://download.oracle.com/javase/6/docs/api/),
are included in any Sun/Oracle Java SDK distribution,
are probably viewable in your Java IDE, and
and be found using a Google search.
public int solution(final String S, final int K) {
int splitCount = -1;
final int count = (int) Stream.of(S.split(" ")).filter(v -> v.length() > K).count();
if (count > 0) {
return splitCount;
}
final List<String> words = Stream.of(S.split(" ")).collect(Collectors.toList());
final List<String> subStrings = new ArrayList<>();
int counter = 0;
for (final String word : words) {
final StringJoiner sj = new StringJoiner(" ");
if (subStrings.size() > 0) {
final String oldString = subStrings.get(counter);
if (oldString.length() + word.length() <= K - 1) {
subStrings.set(counter, sj.add(oldString).add(word).toString());
} else {
counter++;
subStrings.add(counter, sj.add(word).toString());
}
} else {
subStrings.add(sj.add(word).toString());
}
}
subStrings.forEach(
v -> {
System.out.printf("[%s] and length %d\n", v, v.length());
}
);
splitCount = subStrings.size();
return splitCount;
}
public static void main(final String[] args) {
final MessageSolution messageSolution = new MessageSolution();
final String message = "SMSas5 ABC DECF HIJK1566 SMS POP SUV XMXS MSMS";
final int maxSize = 11;
System.out.println(messageSolution.solution(message, maxSize));
}

Categories