I am trying to split a string like "$ 12,9608,03" and just want the numbers and convert to an integer.
For splitting how should I use split() in java as there is a space after the $ sign.
Tried with following:
String[] arr_1=mystring.Split(“[\$, ] “);
String array1=arr_1[0];
Sopln(array1);
You can do what you want, I believe, using this:
String splited = "$ 12,9608,03".replaceAll("[^0-9]", "");
Then you will have splitted only the numbers by commas, but as String. Then you can use, for each String you got, Integer.valueOf() method.
String[] splitted = mystring.split(" ");
String numb = splitted[1];
Just split on the whitespace.
Just like that:
String[] arr_1=mystring.Split("$");
String array1=arr_1[0].trim();
Sopln(array1);
use space in regular experssion to split the string.
String[] split = str.split("( )");
System.out.println(split[1]);
Some fine answers here, to finish off the whole question
and convert to an integer
Here you are:
String myString = "$ 12,9608,03";
String[] splitted = myString.split(" ");
int numb = Integer.parseInt(splitted[1].replaceAll(",", ""));
System.out.println(numb);
To take just the digits, you'd do better with replace:
mystring.replaceAll("[^0-9]", "")
The first parameter is a regex that matches anything but a digit. So this will return you just the number
Stop being insane. Almost everything you will ever do (applies to all readers) has already been done (often better) by the Apache Commons project.
Read the Apache Commons StringUtils API page, pay attention to the RemoveAll method.
Use the StringUtils.RemoveAll method.
Convert the output from the StringUtils.RemoveAll method to an int;
catch any exceptions and handle them appropriately.
Related
How can I delete everything after first empty space in a string which user selects? I was reading this how to remove some words from a string in java. Can this help me in my case?
You can use replaceAll with a regex \s.* which match every thing after space:
String str = "Hello java word!";
str = str.replaceAll("\\s.*", "");
output
Hello
regex demo
Like #Coffeehouse Coder mention in comment, This solution will replace every thing if the input start with space, so if you want to avoid this case, you can trim your input using string.trim() so it can remove the spaces in start and in end.
Assuming that there is no space in the beginning of the string.
Follow these steps-
Split the string at space. It will create an array.
Get the first element of that array.
Hope this helps.
str = "Example string"
String[] _arr = str.split("\\s");
String word = _arr[0];
You need to consider multiple white spaces and space in the beginning before considering the above code.
I am not native to JAVA Programming but have an idea that it has split function for string.
And the reference you cited in the question is bit complex, while you can achieve the desired thing very easily.
P.S. In future if you make a mind to get two words or three, splitting method is better (assuming you have already dealt with multiple white-spaces) else substring is better.
A simple way to do it can be:
System.out.println("Hello world!".split(" ")[0]);
// Taking 'str' as your string
// To remove the first space(s) of the string,
str = str.trim();
int index = str.indexOf(" ");
String word = str.substring(0, index);
This is just one method of many.
str = str.replaceAll("\\s+", " "); // This replaces one or more spaces with one space
String[] words = str.split("\\s");
String first = words[0];
The simplest solution in my opinion would be to just locate the index which the user wants it to be cut off at and then call the substring() method from 0 to the index they wanted. Set that = to a new string and you have the string they want.
If you want to replace the string then just set the original string = to the result of the substring() method.
Link to substring() method: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)
There are already 5 perfectly good answers, so let me add a sixth one. Variety is the spice of life!
private static final Pattern FIRST_WORD = Pattern.compile("\\S+");
public static String firstWord(CharSequence text) {
Matcher m = FIRST_WORD.matcher(text);
return m.find() ? m.group() : "";
}
Advantages over the .split(...)[0]-type answers:
It directly does exactly what is being asked, i.e. "Find the first sequence of non-space characters." So the self-documentation is more explicit.
It is more efficient when called on multiple strings (e.g. for batch processing a large list of strings) because the regular expression is compiled only once.
It is more space-efficient because it avoids unnecessarily creating a whole array with references to each word when we only need the first.
It works without having to trim the string.
(I know this is probably too late to be of any use to the OP but I'm leaving it here as an alternative solution for future readers.)
This would be more efficient
String str = "Hello world!";
int spaceInd = str.indexOf(' ');
if(spaceInd != -1) {
str = str.substring(0, spaceInd);
}
System.out.println(String.format("[%s]", str));
I am new to java progrmming and came across the StringTokenizer class. The constructor accepts the string to be split and another optional delimiter string each character of which gets treated as an individual delimiter while splitting the original string. I was wondering if there is any way to split the string passing a regex as the delimiter. for example:
String s="34.5xy32.6y45.7x36xy"
StringTokenizer t=new StringTokenizer(s,"xy");
System.out.println(t.nextToken());
System.out.println(t.nextToken());
The actual output is:
34.5
32.6
However, the desired output is:
34.5
32.6y45.7x36
Hope you guys can help. Also, please suggest some way around if it is not possible with StringTokenizer class.
Thanks in advance.
p.s. Is there any way to know which character the StringTokenizer is currently using as delimiter out of the provided set?
Here you would want to use String.split(), this will give you an array with your desired output.
It will take your input and split it around exact matches of your string you provide. StringTokenizer will split around anyone of the set that you provide it rather than a regular expression.
So you change your code to:
String s="34.5xy32.6y45.7x36xy";
String[] splitString = s.split("xy");
System.out.println(splitString [0]);
System.out.println(splitString [1]);
For more complex examples you probably want boundary checking on the array also to make you don't go off the end of the array
Try with this.
String s="34.5xy32.6y45.7x36xy";
final String SPLIT_STR = "xy";
final String mainStr = "34.5xy32.6y45.7x36xy";
final String[] splitStr = mainStr.split(SPLIT_STR);
System.out.println("First Index Of xy : " +
mainStr.indexOf(SPLIT_STR));
for(int index=0; index < splitStr.length; index++) {
System.out.println("Split : " + splitStr[index]);
}
When I split a string in python, adjacent space delimiters are merged:
>>> str = "hi there"
>>> str.split()
['hi', 'there']
In Java, the delimiters are not merged:
$ cat Split.java
class Split {
public static void main(String args[]) {
String str = "hi there";
String result = "";
for (String tok : str.split(" "))
result += tok + ",";
System.out.println(result);
}
}
$ javac Split.java ; java Split
hi,,,,,,,,,,,,,,there,
Is there a straightforward way to get python space split semantics in java?
String.split accepts a regular expression, so provide it with one that matches adjacent whitespace:
str.split("\\s+")
If you want to emulate the exact behaviour of Python's str.split(), you'd need to trim as well:
str.trim().split("\\s+")
Quote from the Python docs on str.split():
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].
So the above is still not an exact equivalent, because it will return [''] for the empty string, but it's probably okay for your purposes :)
Use str.split("\\s+") instead. This will do what you need.
Java uses Regex to split.
so splitting on a single space will absolutely give you many array elements.
Python split, ltrims and rtrims and then takes runs of spaces into a single space when no parameter has been passed.
So it would more properly be
"my string".trim().split("\\s+");
The problem with Niklas B.'s answer is that trim has its own definition of whitespace, i.e., anything with code up to '\u0020'. The following should get close enough to the Python version, including the fix for the empty string:
class TestSplit {
private static final String[] EMPTY = {};
private static String[] pySplit(String s) {
s = s.replaceAll("^\\s+", "").replaceAll("\\s+$", "");
if (s.isEmpty()) return EMPTY;
return s.split("\\s+");
}
}
In java, String.split takes a regex. So you can do str.split(" +") to get python semantics.
I have a string as follows:
2012/02/01,13:27:20,872226816,-1174749184,2136678400,2138578944,-17809408,2147352576
I want to extract the number: 872226816, so in this case I assume after the second comma start reading the data and then the following comma end the reading of data.
Example output:
872226816
s = "2012/02/01,13:27:20,872226816,-1174749184,2136678400,2138578944,-17809408,2147352576";
s.split(",")[2];
Javadoc for String.split()
If the number you want will always be after the 2nd comma, you can do something like so:
String str = "2012/02/01,13:27:20,872226816,-1174749184,2136678400,2138578944,-17809408,2147352576";
String[] line = str.split(",");
System.out.println(line[2]);
Imagine I have this string:
string thing = "sergio|tapia|gutierrez|21|Boston";
In C# I could go:
string[] Words = thing.Split('|');
Is there something similar in Java?
I could use Substring and indexOf methods but it is horribly convoluted. I don't want that.
You can use String.split.
String test = "a|b|c";
String[] splitStr = test.split("\\|"); // {"a", "b", "c"}
String thing = "sergio|tapia|gutierrez|21|Boston";
String[] words = thing.split("\\|");
The problem with "|" alone, is that, the split method takes a regular expression instead of a single character, and the | is a regex character which hava to be scaped with \
But as you see it is almost identical
I would try the String.split method, personally.
Yes, there's something similar.
String[] words = thing.split("|");
It's easy. You just call the split method with a delimiter
String s = "172.16.1.100";
String parts[] = s.split("\\.");
Exactly the same : String.split
Use String.split().
you need to escape the pipe delimiter with \\, someString.split("\\|");