This question already has answers here:
How to convert String to long in Java?
(10 answers)
Closed 6 years ago.
how do you convert a string into a long.
for int you
int i = 3423;
String str;
str = str.valueOf(i);
so how do you go the other way but with long.
long lg;
String Str = "1333073704000"
lg = lg.valueOf(Str);
This is a common way to do it:
long l = Long.parseLong(str);
There is also this method: Long.valueOf(str); Difference is that parseLong returns a primitive long while valueOf returns a new Long() object.
The method for converting a string to a long is Long.parseLong. Modifying your example:
String s = "1333073704000";
long l = Long.parseLong(s);
// Now l = 1333073704000
IF your input is String then I recommend you to store the String into a double and then convert the double to the long.
String str = "123.45";
Double a = Double.parseDouble(str);
long b = Math.round(a);
String s = "1";
try {
long l = Long.parseLong(s);
} catch (NumberFormatException e) {
System.out.println("NumberFormatException: " + e.getMessage());
}
You can also try following,
long lg;
String Str = "1333073704000"
lg = Long.parseLong(Str);
import org.apache.commons.lang.math.NumberUtils;
This will handle null
NumberUtils.createLong(String)
Do this:
long l = Long.parseLong(str);
However, always check that str contains digits to prevent throwing exceptions.
For instance:
String str="ABCDE";
long l = Long.parseLong(str);
would throw an exception but this
String str="1234567";
long l = Long.parseLong(str);
won't.
Use parseLong(), e.g.:
long lg = lg.parseLong("123456789123456789");
Related
String my_expr=editText.getText().toString();
Long val = Long.parseLong(my_expr);
DecimalFormat formatter = new DecimalFormat("#,###,###");
String formattedString = formatter.format(val);
editText1.setText(formattedString);
I've taken the whole expression(my_expr) as a single string value.I applied textWatcher but it doesn't work after operators.
If my_expr is the full expression, i.e. something like "23214+3157x56", then this won't work since Long.parse(my_expr) expects a single number. You need to split the expression string into each number first.
// 23214+3157x56
String my_expr = editText.getText().toString();
// [23214, +, 3157, x, 56]
String[] splitted = my_expr.split("((?<=[-+x/])|(?=[-+x/]))");
StringBuilder formatted = new StringBuilder();
DecimalFormat formatter = new DecimalFormat("#,###,###");
for (String word : splitted) {
try {
double num = Double.parseDouble(word);
formatted.append(formatter.format(num));
} catch (NumberFormatException e) {
formatted.append(word);
}
}
// formatted.toString() -> "23,214+3,157x56"
editText1.setText(formatted.toString(), TextView.BufferType.NORMAL);
The regular expression used to create split should contain all characters you're using as operators. If you have operators that use parentheses or more than one character, this approach won't work and you'll have to change the regular expression used for splitting or create your own parser.
Also I recommend using Double.parseDouble(String) over parsing the expression into longs.
Here a second approach:
include java.text.*;
String expr="23214+3157x56"
String[] oper=expr.split ("[0-9]+")
String[] ls = expr.split ("[-+x/]");
List<String> sl = new ArrayList <> ();
for (String s : ls) {
Long l = Long.parseLong (s);
sl.add (String.format ("%1$,d", l));
}
String res = "";
for (int i = 0; i < sl.size (); ++i) {
res += oper[i] + sl.get(i);
}
jshell:
-> res
| Variable res of type String has value "23.214+ 3.157x 56"
This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 5 years ago.
I have the following string:
String result = "#sequence#A:exampleA#B:exampleB";
I would like to split this string into two strings like this:
String resulta = "sequence";
String resultb = "#A:exampleA#B:exampleB";
How can I do this? I'm new to Java programming language.
Thanks!
if you want typical split, (Specific to your string), you can call substring and get the part of it like below:
String s = "#sequence#A:exampleA#B:exampleB";
String s1= s.substring(1,s.indexOf("#",1));
System.out.println(s1);
String s2= s.substring(s1.length()+1);
System.out.println(s2);
}
Edit as per your comment
String s3= s.substring(s.indexOf("#",1));
System.out.println(s3);
Try,
String result = "#sequence#A:exampleA#B:exampleB", resulta, resultb;
int splitPoint = result.indexOf('#',1);
resulta = result.substring(1, splitPoint);
resultb = result.substring(splitPoint);
System.out.println(resulta+", "+resultb);
String result = "#sequence#A:exampleA#B:exampleB";
if(result.indexOf("#") == 0)
result = result.substring(1, result.length());
String resultA = result.substring(0, result.indexOf("#"));
String resultB = result.substring(resultA.length(), result.length());
I have a problem with String.format In android I want replace { 0 } with my id.
My this code not working:
String str = "abc&id={0}";
String result = String.format(str, "myId");
I think you should use replace method instead of format.
String str = "abc&id={0}";
str.replace("{0}","myId");
you have 2 ways to do that and you are mixing them :)
1.String format:
String str = "abc&id=%s";//note the format string appender %s
String result = String.format(str, "myId");
or
2.Message Format:
String str = "abc&id={0}"; // note the index here, in this case 0
String result = MessageFormat.format(str, "myId");
You have to set your integer value as a seperate variable.
String str = "abc&id";
int myId = 001;
String result = str+myId;
try this,
String result = String.format("abc&id=%s", "myId");
edit if you want more than one id,
String.format("abc&id=%s.id2=%s", "myId1", "myId2");
The syntax you're looking for is:
String str = "abc&id=%1$d";
String result = String.format(str, id);
$d because it's a decimal.
Other use case:
String.format("More %2$s for %1$s", "Steven", "coffee");
// ==> "More coffee for Steven"
which allows you to repeat an argument any number of times, at any position.
I need help to parse a string in Java... I'm very new to Java and am not sure how to go about it.
Suppose the string I want to parse is...
String str = "NC43-EB2;49.21716;-122.667252;49.216757;-122.666235;"
What I would want to do is:
String name = C43
String direction = EB2;
Then what I'd like to do is store 2 coordinates as a pair...
Coordinate c1 = 49.21716;-122.667252;
Coordinate c2 = 49.216757;-122.666235;
And then make a List to store c1 and c2.
So far I have this:
parseOnePattern(String str) {
String toParse = str;
name = toParse.substring(1, toParse.indexOf("-"));
direction = toParse.substring(toParse.indexOf("-", toParse.indexOf(";")));
I'm not sure how to move forward. Any help will be appreciated.
A simple substring function may solve your problem.
String str = "NC43-EB2;49.21716;-122.667252;49.216757;-122.666235;";
String[]s = str.split(";");
String[]n = s[0].split("-");
String name = n[0].substring(1);
String direction = n[1];
String c1 = s[1] +";"+s[2];
String c2 = s[3] +";"+s[4];
System.out.println(name + " " + direction);
System.out.println(c1 + " " + c2);
I hope this helps you.
Welcome to Java and the whole set of operations it allows to perform on Strings. You have a whole set of operations to perform, I will give you the code to perform some of them and get you started :-
public void breakString() {
String str = "NC43-EB2;49.21716;-122.667252;49.216757;-122.666235";
// Will break str to "NC43-EB2" and "49.21716" "-122.667252" "49.216757" "-122.666235"
String [] allValues = str.split(";", -1);
String [] nameValuePair = allValues[0].split("-");
// substring selects only the specified portion of string
String name = nameValuePair[0].substring(1, 4);
// Since "49.21716" is of type String, we may need it to parse it to data type double if we want to do operations like numeric operations
double c1 = 0d;
try {
c1 = Double.parseDouble(allValues[1]);
} catch (NumberFormatException e) {
// TODO: Take corrective measures or simply log the error
}
What I would suggest you is to go through the documentation of String class, learn more about operations like String splitting and converting one data type to another and use an IDE like Eclipse which has very helpful features. Also I haven't tested the code above, so use it as a reference and not as a template.
Ok i made this:
public static void main(String[] args) {
String str = "NC43-EB2;49.21716;-122.667252;49.216757;-122.666235;";
String[] strSplit = str.split(";");
String[] nameSplit=strSplit[0].split("-");
String name=nameSplit[0].replace("N", "");
String direction= nameSplit[1];
String cordanateOne = strSplit[1]+";"+strSplit[2]+";";
String cordanateTwo = strSplit[3]+";"+strSplit[4]+";";
System.out.println("Name: "+name);
System.out.println("Direction: "+direction);
System.out.println("Cordenate One: "+cordanateOne);
System.out.println("Cordenate Two: "+cordanateTwo);
}
Name: C43
Direction: EB2
Cordenate One: 49.21716;-122.667252;
Cordenate Two: 49.216757;-122.666235;
String str3 = "NC43-EB2;49.21716;-122.667252;49.216757;-122.666235;";
String sub = str3.substring(0,4); // sub = NC43
String sub4 = str3.substring(5,9); // sub = EB2;
HashMap<String, String> hm = new HashMap<>();
hm.put(str3.substring(9 ,30), str3.substring(30));
hm.forEach((lat, lot) -> {
System.out.println(lat + " - " + lot); // 49.21716;-122.667252; - 49.216757;-122.666235;
});
//edit if using an array non pairs (I assumed it was lat + lon)
List<String> coordList = new ArrayList<>();
coordList.add(str3.substring(9 ,30));
coordList.add(str3.substring(30));
coordList.forEach( coord -> {
System.out.println(coord);
});
//output : 49.21716;-122.667252;
49.216757;-122.666235;
I can normally identify an integer by typing in int something = 0; to initialize or something.
This time I would like to get an integer like I do a String from a JtextArea.
String strcname = cname.getText();
**int strage = age.getInt();**
String stremail = email.getText();
String strphone = phone.getText();
Obviously I am getting an error here but not sure how to have this excepted as an integer any ideas?
You could use:
int strage = Integer.parseInt(age.getText());