I need to create a summary table at the end of a log with some values that
are obtained inside a class. The table needs to be printed in fixed-width
format. I have the code to do this already, but I need to limit Strings,
doubles and ints to a fixed-width size that is hard-coded in the code.
So, suppose I want to print a fixed-width table with
int,string,double,string
int,string,double,string
int,string,double,string
int,string,double,string
and the fixed widths are: 4, 5, 6, 6.
If a value exceeds this width, the last characters need to be cut off. So
for example:
124891, difference, 22.348, montreal
the strings that need to be printed ought to be:
1248 diffe 22.348 montre
I am thinking I need to do something in the constructor that forces a
string not to exceed a certain number of characters. I will probably
cast the doubles and ints to a string, so I can enforce the maximum width
requirements.
I don't know which method does this or if a string can be instantiated to
behave taht way. Using the formatter only helps with the
fixed-with formatting for printing the string, but it does not actually
chop characters that exceed the maximum length.
You can also use String.format("%3.3s", "abcdefgh"). The first digit is the minimum length (the string will be left padded if it's shorter), the second digit is the maxiumum length and the string will be truncated if it's longer. So
System.out.printf("'%3.3s' '%3.3s'", "abcdefgh", "a");
will produce
'abc' ' a'
(you can remove quotes, obviously).
Use this to cut off the non needed characters:
String.substring(0, maxLength);
Example:
String aString ="123456789";
String cutString = aString.substring(0, 4);
// Output is: "1234"
To ensure you are not getting an IndexOutOfBoundsException when the input string is less than the expected length do the following instead:
int maxLength = (inputString.length() < MAX_CHAR)?inputString.length():MAX_CHAR;
inputString = inputString.substring(0, maxLength);
If you want your integers and doubles to have a certain length then I suggest you use NumberFormat to format your numbers instead of cutting off their string representation.
For readability, I prefer this:
if (inputString.length() > maxLength) {
inputString = inputString.substring(0, maxLength);
}
over the accepted answer.
int maxLength = (inputString.length() < MAX_CHAR)?inputString.length():MAX_CHAR;
inputString = inputString.substring(0, maxLength);
You can use the Apache Commons StringUtils.substring(String str, int start, int end) static method, which is also null safe.
See: http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#substring%28java.lang.String,%20int,%20int%29
and http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/src-html/org/apache/commons/lang/StringUtils.html#line.1961
You can achieve this easily using
shortString = longString.substring(0, Math.min(s.length(), MAX_LENGTH));
If you just want a maximum length, use StringUtils.left! No if or ternary ?: needed.
int maxLength = 5;
StringUtils.left(string, maxLength);
Output:
null -> null
"" -> ""
"a" -> "a"
"abcd1234" -> "abcd1"
Left Documentation
The solution may be java.lang.String.format("%" + maxlength + "s", string).trim(), like this:
int maxlength = 20;
String longString = "Any string you want which length is greather than 'maxlength'";
String shortString = "Anything short";
String resultForLong = java.lang.String.format("%" + maxlength + "s", longString).trim();
String resultForShort = java.lang.String.format("%" + maxlength + "s", shortString).trim();
System.out.println(resultForLong);
System.out.println(resultForShort);
ouput:
Any string you want w
Anything short
Ideally you should try not to modify the internal data representation for the purpose of creating the table. Whats the problem with String.format()? It will return you new string with required width.
Related
I need to replace first and middle char in string but without builder and etc, just with replace but idk how to make it.
String char = JOptionPane.showInputDialog(null, "Input string with more than 3 char");
if (char.length() < 3) {
JOptionPane.showMessageDialog(null, "Wrong input");
I just made this code and that is it, idk how to continue.
Example: input - pniut
I tried with smth like char.length / 2 but cant.
You can convert your string to a character array, and then swap the characters at 0 and middle position. Then convert the array back to String. e.g. I hard coded 2 here but like you mentioned in comments, you will need to figure out the character at the middle position.
String str = "input";
int mid = -1;
if(str.length() % 2 == 0) {
str.length() / 2 - 1
} else {
str.length() / 2;
}
char[] arr = str.toCharArray();
char temp = '0';
temp = arr[0];
arr[0] = arr[mid];
arr[mid] = temp;
String.valueOf(arr);
The value of the middle character, you will need to find out, like you said in the comments.
Since String objects are immutable, converting the original String to a char[] via toCharArray(), replace the characters, then making a new String from char[] via the String(char[]) constructor would work as shown below:
char[] c = character.toCharArray();
// Change characters at desired indicies
c[0] = 'p'; // first character
c[character.length()/2] = 'i'; // approximate middle character
String newString = new String(c);
System.out.println(newString); // "pniut"
Simple answer: not possible (for generic cases).
Meaning: all variants of String.replace() work by replacing one thing with another. There is no notion of using an index anywhere. So you can't say "replace index 1 with A" and "index 3 with B".
The simply solution is to push the string into a char[], to then swap/replace individual characters via index.
I'm betting the goal of the lesson is to learn how to use the API. So would start here Java API. Go to java.lang.String.
I would focus on the .toCharArray() method and the constructor that takes a char[] as an argument. You need to do this because a String is immutable, and cannot be changed. A char[], however can be altered, allowing you to modify the first and middle slots. You can then take your altered array and convert it back into a String.
I am aware that we can use String Utils library. But what if the String has only "0". It returns " ". Do we have any other way to remove leading 0 for all other strings except for "0".
Here is the scenario:
So, I am truncating the value of the Strings that are being entered by the users on the client side.All the inputs are taken in form of strings. For example if the user enters the department number as 009, I will truncate it to 9. For 08 it should be 8. But , here there is a department with 0. So when user is entering only 0, this method removes 0 too
Also what if the input is 000. I need last 0 with out being truncated.
I am aware that we can use String Utils library. But what if the String has only "0". It returns " ". Do we have any other way to remove leading 0 for all other strings except for "0".
You can create your own utility method that does exactly what you want.
Well you still haven't answered my question about whether the department can be alphanumeric or just numeric.
Based on your examples you could just convert the String to an Integer. The toString() implementation of an Integer removes leading zeroes:
System.out.println( new Integer("008").toString() );
System.out.println( new Integer("000").toString() );
System.out.println( new Integer("111").toString() );
If the string can contain alphanumeric the logic would be more complex, which is why it is important to define the input completely.
For an alphanumeric string you could do something like:
StringBuilder sb = new StringBuilder("0000");
while (sb.charAt(0) == '0' && sb.length() > 1)
sb.deleteCharAt(0);
System.out.println(sb);
Or, an even more efficient implementation would be something like:
int i = 0;
while (product.charAt(i) == '0' && i < product.length() - 1)
i++;
System.out.println( product.substring(i) );
The above two solutions are the better choice since they will work for numeric and alphanumeric strings.
Or you could even use the StringUtils class to do what you want:
String result = StringUtils.removeleadingZeroes(...) // whatever the method is
if (result.equals(" "))
result = "0";
return result;
In all solutions you would create a method that you pass parameter to and then return the String result.
If you want to use a regex based approach, then one option would be to greedily remove all zeroes, starting from the beginning, so long as we do not replace the final character in the string. The following pattern does this:
^0+(?=.)
The lookahead ensures that there is at least one digit remaining, hence, a final zero will never be replaced.
String input1 = "040008";
String input2 = "000008";
String input3 = "000000";
input1 = input1.replaceAll("^0+(?=.)", "");
input2 = input2.replaceAll("^0+(?=.)", "");
input3 = input3.replaceAll("^0+(?=.)", "");
System.out.println(input1);
System.out.println(input2);
System.out.println(input3);
40008
8
0
Demo
By the way, I like the answer by #camickr and you should consider that as an option.
How can I convert a float to a String and always get a resulting string of a specified length?
For example, if I have
float f = 0.023f;
and I want a 6 character string, I'd like to get 0.0230. But if I want to convert it to a 4 character string the result should be 0.02. Also, the value -13.459 limited to 5 characters should return -13.4, and to 10 characters -13.459000.
Here's what I'm using right now, but there's gotta be much prettier ways of doing this...
s = String.valueOf(f);
s = s.substring(0, Math.min(strLength, s.length()));
if( s.length() < strLength )
s = String.format("%1$-" + (strLength-s.length()) + "s", s);
From java.util.Formatter documentaion: you can use g modifier, precision field to limit number to specific number of characters and width field for padding it to column width.
String.format("%1$8.5g", 1000.4213);
https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html
Though precision doesn't include dot and exponent length – only digits in mantissa counted.
By keeping extra place for dot and cutting extra digits from fractional part if string is significantly wider that could be solved too.
String num = String.format("%1$ .5g", input);
if (num.length > 6)
num = num.substring(0, 2) + num.substring(7); //100300 => ' 1e+05'; 512.334 => ' 512.33'
Scientific format of number always follows strict set of rules, so we don't have to search for dot inside string to cut fraction out of string if sign is always included (or, like in case above – replaced by space character for positive numbers).
I would like to append "0" string when an int is lower than 5. I have tried this
if(allItems_filtered.results(i).min_sale_unit_price.length() < 5){
calc = 5 - allItems_filtered.results(i).min_sale_unit_price.length();
min_sale_unit_price = String.format("%0" + calc + "d", allItems_filtered.results(i).min_sale_unit_price);
}
int calc is the amount of "0" it has to append in front of the min_sale_unit_price string
Which returns this error:
%d can't format java.lang.String arguments
Which is quite self explaining but I do not know how to the the same but then to a string.
It is telling you that you are trying to format a String, but %d is refering to an int, you need to convert the String to int an it will work. Also you don't need to calculate how many zeros you need, if you use %05d it will automatically fill the number till it's length isn't 5
min_sale_unit_price = String.format("%05d", Integer.valueOf(allItems_filtered.results(i).min_sale_unit_price));
Take for an example
Log.d("123?", String.format("%05d", 123));
Will print out
00123
If you take a number that is larger in size than five, it will not append anything
Log.d("123?", String.format("%05d", 123456));
Will result
123456
In Java, I have a String:
Jamaica
I would like to remove the first character of the string and then return amaica
How would I do this?
const str = "Jamaica".substring(1)
console.log(str)
Use the substring() function with an argument of 1 to get the substring from position 1 (after the first character) to the end of the string (leaving the second argument out defaults to the full length of the string).
public String removeFirstChar(String s){
return s.substring(1);
}
In Java, remove leading character only if it is a certain character
Use the Java ternary operator to quickly check if your character is there before removing it. This strips the leading character only if it exists, if passed a blank string, return blankstring.
String header = "";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);
header = "foobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);
header = "#moobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);
Prints:
blankstring
foobar
moobar
Java, remove all the instances of a character anywhere in a string:
String a = "Cool";
a = a.replace("o","");
//variable 'a' contains the string "Cl"
Java, remove the first instance of a character anywhere in a string:
String b = "Cool";
b = b.replaceFirst("o","");
//variable 'b' contains the string "Col"
Use substring() and give the number of characters that you want to trim from front.
String value = "Jamaica";
value = value.substring(1);
Answer: "amaica"
You can use the substring method of the String class that takes only the beginning index and returns the substring that begins with the character at the specified index and extending to the end of the string.
String str = "Jamaica";
str = str.substring(1);
substring() method returns a new String that contains a subsequence of characters currently contained in this sequence.
The substring begins at the specified start and extends to the character at index end - 1.
It has two forms. The first is
String substring(int FirstIndex)
Here, FirstIndex specifies the index at which the substring will
begin. This form returns a copy of the substring that begins at
FirstIndex and runs to the end of the invoking string.
String substring(int FirstIndex, int endIndex)
Here, FirstIndex specifies the beginning index, and endIndex specifies
the stopping point. The string returned contains all the characters
from the beginning index, up to, but not including, the ending index.
Example
String str = "Amiyo";
// prints substring from index 3
System.out.println("substring is = " + str.substring(3)); // Output 'yo'
you can do like this:
String str = "Jamaica";
str = str.substring(1, title.length());
return str;
or in general:
public String removeFirstChar(String str){
return str.substring(1, title.length());
}
public String removeFirst(String input)
{
return input.substring(1);
}
The key thing to understand in Java is that Strings are immutable -- you can't change them. So it makes no sense to speak of 'removing a character from a string'. Instead, you make a NEW string with just the characters you want. The other posts in this question give you a variety of ways of doing that, but its important to understand that these don't change the original string in any way. Any references you have to the old string will continue to refer to the old string (unless you change them to refer to a different string) and will not be affected by the newly created string.
This has a number of implications for performance. Each time you are 'modifying' a string, you are actually creating a new string with all the overhead implied (memory allocation and garbage collection). So if you want to make a series of modifications to a string and care only about the final result (the intermediate strings will be dead as soon as you 'modify' them), it may make more sense to use a StringBuilder or StringBuffer instead.
I came across a situation where I had to remove not only the first character (if it was a #, but the first set of characters.
String myString = ###Hello World could be the starting point, but I would only want to keep the Hello World. this could be done as following.
while (myString.charAt(0) == '#') { // Remove all the # chars in front of the real string
myString = myString.substring(1, myString.length());
}
For OP's case, replace while with if and it works aswell.
You can simply use substring().
String myString = "Jamaica"
String myStringWithoutJ = myString.substring(1)
The index in the method indicates from where we are getting the result string, in this case we are getting it after the first position because we dont want that "J" in "Jamaica".
Another solution, you can solve your problem using replaceAll with some regex ^.{1} (regex demo) for example :
String str = "Jamaica";
int nbr = 1;
str = str.replaceAll("^.{" + nbr + "}", "");//Output = amaica
My version of removing leading chars, one or multiple. For example, String str1 = "01234", when removing leading '0', result will be "1234". For a String str2 = "000123" result will be again "123". And for String str3 = "000" result will be empty string: "". Such functionality is often useful when converting numeric strings into numbers.The advantage of this solution compared with regex (replaceAll(...)) is that this one is much faster. This is important when processing large number of Strings.
public static String removeLeadingChar(String str, char ch) {
int idx = 0;
while ((idx < str.length()) && (str.charAt(idx) == ch))
idx++;
return str.substring(idx);
}
##KOTLIN
#Its working fine.
tv.doOnTextChanged { text: CharSequence?, start, count, after ->
val length = text.toString().length
if (length==1 && text!!.startsWith(" ")) {
tv?.setText("")
}
}