There is e.x 2.52549856E8 float number.
What I want is simply make it 25.2549856E8, that's it, everything else can stay.
I sought for solution and all I found was with bunch of string examples.
I get pure float number. Should I convert it to String first? Is there a simpler way to do this?
if you want to just move the dot one digit to the right, you can use following snippet, which uses String#substring() to cut the String into the right parts and then concatenates them again:
String number = String.valueOf(2.52549856E8f);
int index = number.indexOf('.');
String formatted =
number.substring(0, index) +
number.substring(index + 1, index + 2) +
'.' +
number.substring(index + 2);
number.substring(0, index) cuts the first digit out
number.substring(index + 1, index + 2) cuts the second digit out
'.' inserts the new dot
number.substring(index + 2) appends the rest of the number
The same can be done with regex:
String number = String.valueOf(2.52549856E8f);
String formatted = number.replaceAll("^(\\d)\\.(\\d)(\\d+E\\d+)$", "$1$2.$3");
Related
This is probably an easy question but I haven't been able to figure it out. I want to find the next letter (A to Z) in a string after a certain point in the string. The result I want from below is for the string money to be "$5. 00" but num2 always comes up as -1.
String text = "hello$5. 00Bla bla words that don't matter"
int num1 = text.indexOf('$');
int num2 = text.indexOf("[a-zA-Z]" , num1 + 1); // Always results in -1
String money = text.substring(num1, num2);
To find the first letter following a $ dollar sign, using regex, you can use the following regex:
\$\P{L}*\p{L}
Explanation:
\$ Match a $ dollar sign
\P{L}* Match 0 or more characters that are not Unicode letters
\p{L} Match a Unicode letter
The index of the letter is then the last character of the matched substring, i.e. one character before the end() of the match.
Example
String text = "hello$5. 00Bla bla words that don't matter";
Matcher m = Pattern.compile("\\$\\P{L}*\\p{L}").matcher(text);
if (m.find()) {
int idx = m.end() - 1;
System.out.println("Letter found at index " + idx + ": '" + text.substring(idx) + "'");
}
Output
Letter found at index 11: 'Bla bla words that don't matter'
UPDATE
It seems the actual question was slightly different than answered above, so to capture the text from $ dollar sign (inclusive) and all following characters up to first letter (exclusive) or end of string, use this regex:
\$\P{L}*
Example
String text = "hello$5. 00Bla bla words that don't matter";
Matcher m = Pattern.compile("\\$\\P{L}*").matcher(text);
if (m.find()) {
String money = m.group();
System.out.println("money = \"" + money + "\"");
}
Output
money = "$5. 00"
This is untested, as my workstation isn't set up for Java 9, but using that release, you should be able to do this:
String result = text.substring(text.indexOf('$'), text.length())
.takeWhile(ch -> !Character.isAlphabetic(ch))
.map(Object::toString).collect(Collectors.joining());
result will evaluate to $5. 00
Note: Stream<T>#takeWhile is a Java 9 feature
Thanks for the help everyone. I found a way to do this without using regex.
String money = "";
while (!Character.isLetter(text.charAt(num1))) {
money = money + text.charAt(num1);
num1++;
}
It might need some work later but it seems to work.
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 have a special kind of Strings in Java that has a sequence of zeros and some short sequence of characters between them like those:
"0000000000TT0000TU0000U0"
"0000000000TL"
"0000000000TL0000TM"
I want to count the number of sequences that are different from zeros.
for example:
"0000000000TT0000TU0000U0" will return 3
"0000000000TL" will return 1
"0000000000TL0000TM" will return 2
"000000" will return 0.
Any short and easy way to do it (maybe some Java String build option or regex of some kinde)?
Thanks
Use a negated character class to match any character but not of 0.
Matcher m = Pattern.compile("[^0]+").matcher(s);
int i = 0;
while(m.find()) {
i = i + 1;
}
System.out.println("Total count " + i);
DEMO
I have one String generated of random characters that will encrypt another String given by the user by adding the first character from the String with the first character of the given String. It's working fine, but if the user were to enter multiple words with spaces in between, I want to choose the next character of the first String rather than code the space itself. Is that possible? This is what I have:
(random is the coded string and sentenceUpper is string given by user)
public static void encrypt(String sentenceUpper){
String newSentence = "";
for(int i = 0; i < sentenceUpper.length(); i++){
char one = random.charAt(i);
char two = sentenceUpper.charAt(i);
if(one < 'A' || one > 'Z'){
two = sentenceUpper.charAt(1 + i);}
char result = (char)((one + two)%26 + 'A');
newSentence += "" + result;
}
EDIT FOR BETTER EXPLANATION:
I have:
String random = "WFAZYZAZOHS";
I would like to code user input:
String upperCase: "YOU GO";
So, I'm going to take Y + L = U, etc...
to get :
"UTUSEN
"
But I see that there's a space in "YOU GO" , So I'd like to change it to:
WFA ZY + YOU GO = UTU SE.
I hope that's better explained.
The simplest way to do this would probably be to use an if statement to run the code in the loop only if the character is not a space. If you don't want to skip the character in the random string, you would need a separate variable to track the current character index in that string.
Example: Put this after defining one and two and put the rest of the loop inside it:
if(two==' '){
...
}
Then, add the space in the output:
else{
newSentence+=" ";
}
I have a String like:
AB524D000000000000231200000001D0000000000000000524
The length of string is 50. Above string is one. this type of string may have lenght 250 ie. five string example:
AB524D000000000000231200000001D0000000000000000524AB524D000000000000231200000001D0000000000000000524AB524D000000000000231200000001D0000000000000000524AB524D000000000000231200000001D0000000000000000524AB524D000000000000231200000001D0000000000000000524.
Now my requirement is I need to change D to C.
I used following code to replace for one string:
String code = key.substring(0, 2);
String currency = key.substring(2, 5);
String type = key.substring(5, 6);
String amount = key.substring(6, 22);
String rate = key.substring(22, 30);
String type2 = key.substring(30, 31);
String rAmount = key.substring(31, 47);
String currency2 = key.substring(47, 50);
String finalReq = code + currency + "C" + amount + rate + "C" + rAmount + currency2;
I got following output:
AB524C000000000000231200000001C0000000000000000524
this is good for one string I mean 50 length string. But string length may 0-250 (string one to 5) but pattern is same like : AB524D000000000000231200000001D0000000000000000524.
Which is the best logic to fulfill my requirement ?.
Note: I can not do string.replaceAll('D','C') because my zeroth and first index has character I mean it may have also D.
I would say that
replaceAll("\\G(.{5})D(.{24})D(.{19})", "$1C$2C$3")
should do the trick but I don't know if your string will only contain data in format you described or if you want to replace only D or any character that can be in places that D is.
replaceAll uses regex as first parameter, and String that can use results of that regex as second parameter. In regex
. dot represents any character except new line
.{x} represents series of any characters that is length x like .{3} can match AbZ or 1X9,
regex inside parenthesis (...) will create group, and each group has its unique number. This number can be used later for example in replacement String via $x where x is number of group
so (.{5})D(.{24})D(.{19}) will match any 5 characters (and store them in group 1), then D then 24 characters (and create store them in group 2) then D and lastly any 19 characters (and store them in group 3)
in replacement "$1C$2C$3" I will use strings that ware matched in first group, then instead of D will put C then will include match from group 2, then again instead of D will put C and after that include last part of match (last 19 characters after second D stored in group 3)
Also assure match could be done only every 50 characters from start of the string I will add \\G represents start of the string or previously match (so there can't be any characters between previous match and current match).
Just use java's String replace method.
String old = "AB524D000000000000231200000001D0000000000000000524AB524D000000000000231200000001D0000000000000000524AB524D000000000000231200000001D0000000000000000524AB524D000000000000231200000001D0000000000000000524AB524D000000000000231200000001D0000000000000000524";
String output = old.replace('D', 'C');
if you are sure that every string is 50 char so :
index = finalReq.length() % 50;
for(int i = 0; i<index; i++){
String code = key.substring(0 + 50 * i, 2 + 50 * i);
String currency = key.substring(2 + 50 * i , 5 + 50 * i);
...
replace ...
}