How can one extract number of trailing zeros from String - java

I want to extract trailing zeros from a string for eg
//8320987112741390144276341183223364380754172606361245952449277696409600000000000000
should yield
14
my approach was to first find the length of above string then subtract it by length of the
stripped trailing zero string.
I tried to find the later using BigDecimal stripTrailingZeros() method but it is only removing zeros after decimal
for eg
1200.000 is converted to 1200 by stripTrailingZeros() method but i want 12 as output
any idea how to solve this problem?

The simplest option would probably be to use String.replaceAll:
text = text.replaceAll("[0.]*$", "");
The $ makes sure it's only trimming the end of the string.
Note that if you start with "0" you'll end up with an empty string - think about what you want the result to be in that situation.

If you want the length of trailing zeroes, you could do this regex :
public static void main(String[] args) {
String s = "8320987112741390144276341183223364380754172606361245952449277696409600000000000000";
Pattern p = Pattern.compile("0+$");
Matcher m = p.matcher(s);
m.find();
String val = m.group();
System.out.println(val);
System.out.println(val.length());
}
O/P :
00000000000000
14

well - this is simple but a compute-intesiv solution...
String str = "8320987112741390144276341183223364380754172606361245952449277696409600000000000000";
System.out.println(str);
int count = 0;
char c = '0';
do {
c = str.charAt(str.length()-1);
if (c == '0' ){
str = str.substring(0, str.length() - 1);
count ++;
}
}while(c == '0' );
System.out.println(str);
System.out.println("amount:"+amount);
but it's a very obvious solution... (just remove last zero...until there is no more...)

Does this answer fulfills your requirement?
String str = "8320987112741390144276341183223364380754172606361245952449277696409600000000000000";
String withoutTrailingZeroes = "";
for (int i = str.length() - 1; i >= 0; i--) {
String charFromString = Character.toString(str.charAt(i));
if (charFromString.equals("0")) {
withoutTrailingZeroes += str.charAt(i);
} else {
break;
}
}
System.out.println(str);
System.out.println(str.replace(withoutTrailingZeroes, "")); // string without trailing zeros
System.out.println(withoutTrailingZeroes); // trailing zeroes
System.out.println(withoutTrailingZeroes.length()); // trailing zeroes length

OK, expanding on Jon's answer, and assuming that you don't want to count the decimal point, then the following code should cope with both integers and decimal numbers in your string:
// Start by taking note of the original string length
int startLength = text.length();
// Remove any trailing zeroes
text = text.replaceAll("0*$", "");
// Remove any zeroes immediately to the left of any trailing decimal point
text = text.replaceAll("0*.$", ".");
// Find the number of zeroes by subtracting the lengths
int numZeroes = startLength - text.length();
or if you want it in a single statement:
int numZeroes = text.length() - text.replaceAll("0*$", "").replaceAll("0*.$", ".").length();
Which looks horrible, but has the advantage of not altering the original string.

Related

Get index of 3rd comma

For example I have this string params: Blabla,1,Yooooooo,Stackoverflow,foo,chinese
And I want to get the string testCaseParams until the 3rd comma: Blabla,1,Yooooooo
and then remove it and the comma from the original string so I get thisStackoverflow,foo,chinese
I'm trying this code but testCaseParams only shows the first two values (gets index of the 2nd comma, not 3rd...)
//Get how many parameters this test case has and group the parameters
int amountOfInputs = 3;
int index = params.indexOf(',', params.indexOf(',') + amountOfInputs);
String testCaseParams = params.substring(0,index);
params = params.replace(testCaseParams + ",","");
You can hold the index of the currently-found comma in a variable and iterate until the third comma is found:
int index = 0;
for (int i=0; i<3; i++) index = str.indexOf(',', index);
String left = str.substring(0, index);
String right = str.substring(index+1); // skip comma
Edit: to validate the string, simply check if index == -1. If so, there are not 3 commas in the string.
One option would be a clever use of String#split:
String input = "Blabla,1,Yooooooo,Stackoverflow,foo,chinese";
String[] parts = input.split("(?=,)");
String output = parts[0] + parts[1] + parts[2];
System.out.println(output);
Demo
One can use split with a limit of 4.
String input = "Blabla,1,Yooooooo,Stackoverflow,foo,chinese";
String[] parts = input.split(",", 4);
if (parts.length == 4) {
String first = parts[0] + "," + parts[1] + "," + parts[2];
String second = parts[3]; // "Stackoverflow,foo,chinese"
}
You can split with this regex to get the 2 pats:
String[] parts = input.split("(?<=\\G.*,.*,.*),");
It will result in parts equal to:
{ "Blabla,1,Yooooooo", "Stackoverflow,foo,chinese" }
\\G refers to the previous match or the start of the string.
(?<=) is positive look-behind.
So it means match a comma for splitting, if it is preceded by 2 other commas since the previous match or the start of the string.
This will keep empty strings between commas.
I offer this here just as a "fun" one line solution:
public static int nthIndexOf(String str, String c, int n) {
return str.length() - str.replace(c, "").length() < n ? -1 : n == 1 ? str.indexOf(c) : c.length() + str.indexOf(c) + nthIndexOf(str.substring(str.indexOf(c) + c.length()), c, n - 1);
}
//Usage
System.out.println(nthIndexOf("Blabla,1,Yooooooo,Stackoverflow,foo,chinese", ",", 3)); //17
(It's recursive of course, so will blow up on large strings, it's relatively slow, and certainly isn't a sensible way to do this in production.)
As a more sensbile one liner using a library, you can use Apache commons ordinalIndexOf(), which achieves the same thing in a more sensible way!

How to insert a space in a charArray in an exact position [Java]

My problem is that I'm getting a String and I need to check if there is a space in the 4th position but starting from the end. If in this position there is not a space, I should insert it.
For example:
I get this String: TW12EF, need to get it like this: TW1 2EF
First of all I get the 4 last characters in a char array because I also need to check if they are numbers or letters.
With this method I check if there is a space:
public static boolean isSpace(){
return String.valueOf(charArray[0]).matches("[ \\t\\n\\x0B\\f\\r]");
}
charArray contains the last 4 characters of the input String
If charArray[0] wouldn't be a space, I want to insert a space in the 2nd place (charArray[1])
If there is something that I can correct in the question to make it easier to understand, just let me know and I will try to make it better for next questions.
A simple and direct solution (most likely faster than using a regular expression) is to get the 4th to the last character (if it exists), and if it isn't a white-space, insert a space at that position.
public static void main(String[] args) {
String str = "TW12EF";
int insertPos = str.length() - 4;
if (insertPos >= 0) {
char ch = str.charAt(insertPos);
if (!Character.isWhitespace(ch)) {
str = new StringBuilder(str).insert(insertPos + 1, ' ').toString();
}
}
System.out.println(str);
}
A whitespace is determined by invoking isWhitespace, which returns true for space but also tabs or line feeds, like you did in your question. The character is inserted by leveraging the StringBuilder#insert method, which is more direct that taking 2 substrings and concatenating them.
A quick, dirty regex will help :
String p = "TW12EF";
System.out.println(p.replaceAll("(.)\\s*(\\S.{2})$", "$1 $2")); // Select a character followed by 0 or more spaces and followed by 3 non-space characters. And replace multiple spaces if they exist with a single space
O/P :
TW1 2EF
Also works if there are one or more spaces after the 3rd char (from the left)
As char is a primitive data type, the comparison can be done simply with
if (charArray[0] == ' ') {
char[] temp = new char[5];
temp[0] = ' ';
for (int i = 1; i <= 4; i++) {
temp[i] = charArray[i - 1];
}
charArray = temp;
}
You could use something like:
public static void main(String[] args) {
String str = "TW12EF";
processStr(str);
}
public static final int SPACE_POS = 4, OFFSET = 1;
public static String processStr(String str)
{
if(!Character.isWhitespace(str.charAt(str.length() - SPACE_POS)))
{
str = String.format("%s %s", str.substring(0, str.length() - SPACE_POS + OFFSET), str.substring(SPACE_POS - OFFSET));
}
return str;
}
Like this?
` String s="TW12EF";
String result="";
int length=s.length();
for(int i=length-1;i>-1;i--){
if(i==length-4&&s.charAt(i)!=' '){
result+=" ";
}
result+=s.charAt(length-i-1);
}
System.out.println(result);`

Find first sequence of numbers in a string?

So first of all i would like to clear things off by saying that this is for a Minecraft plugin. So I have a method to spawn some mobs (You dont know what mobs it is), and give them custom names. The names are based on numbers. But I also have a sequence of characters in its name. So for instance if the name for the mob was "355 Blaze" it would return an int of 355, and cut the rest out. How should I do this? Currently I use substring but it doesnt work as if the number goes above 9 it will return the first number only.
If its separated by space, use substring based on the location of first space:
Integer mobId = new Integer(fullMobName.substring(0, fullMobName.indexOf(" ")));
Simply use a regex.
private final static Pattern p = Pattern.compile("\\d+");
static String firstNum(String s) {
Matcher m = p.matcher(s);
return m.find() ? m.group() : null;
}
You can use a regex expression in replace method
String s = "355 Blaze";
s.replaceAll("[A-Za-z\\s]+", "");
Then you can cast to int.
Do it without a regex (assuming the number is positive and fits in an int):
int i = 0;
// Skip past non-digits.
while (i < s.length() && !Character.isDigit(s.charAt(i))) {
++i;
}
if (i < s.length()) {
int num = 0;
// Accumulate the digits into the result.
while (i < s.length() && Character.isDigit(s.charAt(i))) {
num = 10 * num + Character.getNumericValue(s.charAt(i));
++i;
}
return num;
}
// No digits found.
throw new NoSuchElementException("No digits found!");
If it only contains digits followed by letters( with possibly an optional space), this will also work:
String ss[] = original.split("a-zA-Z ]", 2);
//ss[0] contains the numbers

Remove leading zeros from a number in a string

I wanna trim this string.
"0000819780"
How i can get just the "819780" part.
I can do it with my way, just curious is there any "elegant" or "right" way to do this.
I hope this works:
try {
int i = Integer.parseInt(yourString);
System.out.println(i);
} catch(NumberFormatException e) {
// the string is not a number
}
There are many ways you might remove leading zeros from your String; one approach, iterate the String from left to right stopping at the next to the last character (so you don't erase the final digit) stop if you encounter a non-zero and invoke String.substring(int) like
String str = "0000819780";
for (int i = 0, length = str.length() - 1; i < length; i++) {
if (str.charAt(i) != '0') {
str = str.substring(i);
break;
}
}
System.out.println(str);
Alternatively, parse the String like
int v = Integer.parseInt(str);
System.out.println(v);
Alternative:
Using Apache Commons StringUtils class:
StringUtils.stripStart(String str, String stripChars);
For your example:
StringUtils.stripStart("0000819780", "0"); //should return "819780"
An elegant pure java way is just "0000819780".replaceFirst("^0+(?!$)", "")
If the input is always a number and you want to remove only the beginning zeroes, just parse it into an integer. If you want it in string format, parse it back.
String a = "0000819780";
System.out.println(Long.parseLong(a));
Check https://ideone.com/7NMxbE for a running code.
If it can have values other than numbers, you would need to catch NumberFormatException
while(str.length() >= 1 && str.charAt(0) == '0')
str = str.substring(1);
Double abc = Double.parseDouble("00346632");
String xyz = String.format("%.0f", abc);

How to replace the n th occurance of a character in a String ?

I need to replace all commas after the 5th one. So if a String contains 10 commans, I want to leave only the first 5, and remove all subsequent commas.
How can I do this ?
String sentence = "Test,test,test,test,test,test,test,test";
String newSentence = sentence.replaceAll(",[6]","");
Just capture all the characters from the start upto the 5th comma and match all the remaining commas using the alternation operator |. So , after | should match all the remaining commas. By replacing all the matched chars with $1 will give you the desired output.
sentence.replaceAll("^((?:[^,]*,){5})|,", "$1");
DEMO
In case you were wondering how to solve this problem without using regular expressions... There are libraries that could make your life easier but here is the first thought that came to mind.
public String replaceSpecificCharAfter( String input, char find, int deleteAfter){
char[] inputArray = input.toCharArray();
String output = "";
int count = 0;
for(int i=0; i <inputArray.length; i++){
char letter = inputArray[i];
if(letter == find){
count++;
if (count <= deleteAfter){
output += letter;
}
}
else{
output += letter;
}
}
return output;
}
Then you would invoke the function like so:
String sentence = "Test,test,test,test,test,test,test,test";
String newSentence = replaceSpecificCharAfter(sentence, ',', 6);

Categories

Resources