Suppose I have String s = "123 USA" , how can I obtain only the number i.e '123' that is in the String? By that I mean what is the most efficient way of doing it?
Split the String on the space character.
For each String in the resulting String[], use the method from this answer to determine whether it is a valid integer or not. If it is a valid integer, then output that integer. Otherwise, ignore it.
If you know where the numbers are in the the string, i would do something like this.
String[] split = s.split();
This will give you an array equivalent to
String[] split = ["123", "USA"];
The split function will default to splitting by spaces(I believe).
From there you can use
int num = Integer.parseInt(split[0]);
// num = 123;
to convert the fist index of the split array into an int.
s.replaceAll("\\D+", " ").trim()
\\D+ matches non-digits
trim() clears whitespace
Example:
String testString = " ##!#! (!#)!# 123 USA 312";
Output: 123 312
If there is more than one number, the next step may be to use String.split().
To convert a String to an integer: Integer.parseInt(string)
Related
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.
I need to extract the desired string which attached to the word.
For example
pot-1_Sam
pot-22_Daniel
pot_444_Jack
pot_5434_Bill
I need to get the names from the above strings. i.e Sam, Daniel, Jack and Bill.
Thing is if I use substring the position keeps on changing due to the length of the number. How to achieve them using REGEX.
Update:
Some strings has 2 underscore options like
pot_US-1_Sam
pot_RUS_444_Jack
Assuming you have a standard set of above formats, It seems you need not to have any regex, you can try using lastIndexOf and substring methods.
String result = yourString.substring(yourString.lastIndexOf("_")+1, yourString.length());
Your answer is:
String[] s = new String[4];
s[0] = "pot-1_Sam";
s[1] = "pot-22_Daniel";
s[2] = "pot_444_Jack";
s[3] = "pot_5434_Bill";
ArrayList<String> result = new ArrayList<String>();
for (String value : s) {
String[] splitedArray = value.split("_");
result.add(splitedArray[splitedArray.length-1]);
}
for(String resultingValue : result){
System.out.println(resultingValue);
}
You have 2 options:
Keep using the indexOf method to get the index of the last _ (This assumes that there is no _ in the names you are after). Once that you have the last index of the _ character, you can use the substring method to get the bit you are after.
Use a regular expression. The strings you have shown essentially have the pattern where in you have numbers, followed by an underscore which is in turn followed by the word you are after. You can use a regular expression such as \\d+_ (which will match one or more digits followed by an underscore) in combination with the split method. The string you are after will be in the last array position.
Use a string tokenizer based on '_' and get the last element. No need for REGEX.
Or use the split method on the string object like so :
String[] strArray = strValue.split("_");
String lastToken = strArray[strArray.length -1];
String[] s = {
"pot-1_Sam",
"pot-22_Daniel",
"pot_444_Jack",
"pot_5434_Bill"
};
for (String e : s)
System.out.println(e.replaceAll(".*_", ""));
for example, i have the string "12,456,544,233" from the user input,
I want to take each number that is separated by commas and push each one into
a Stack, converting it to an int in the process because the Stack is .
(array implementation of a stack by the way)
So 12 would be at 0, 456 at 1, 544 at 2, etc...
I KNOW I have to use the Integer class to parse, but just not sure how to setup the loop to do everything, if i didn't provide enough info, ask and I will do so!
thanks.
The code I tried:
String input = scan.nextLine();
stack.push(Integer.parseInt(String.valueOf(input.charAt(2))));
Sounds like homework. so just giving some hints
you can use String.split method to split the string into tokens separated by commas
now traverse the array that you get after split and push to stack.
N.B. if it is really a homework then may be you need to implement your own split
Here is how you can split strings
String string = "12,456,544,233";
String[] individualStrings = string.split(",");
split() method Splits this string around matches of the given regular expression.
Next, you can interate over string array and convert each element into integer.
for(int i = 0; i < individualStrings.length; i++)
{
int m = Integer.parseInt(individualStrings[i]);
}
Cheers !!
I am trying to parse the certain name from the filename.
The examples of File names are
xs_1234323_00_32
sf_12345233_99_12
fs_01923122_12_12
I used String parsedname= child.getName().substring(4.9) to get the 1234323 out of the first line. Instead, how do I format it for the above 3 to output only the middle numbers(between the two _)? Something using split?
one line solution
String n = str.replaceAll("\\D+(\\d+).+", "$1");
most efficent solution
int i = str.indexOf('_');
int j = str.indexOf('_', i + 1);
String n = str.substring(i + 1, j);
String [] tokens = filename.split("_");
/* xs_1234323_00_32 would be
[0]=>xs [1]=> 1234323 [2]=> 00 [3] => 32
*/
String middleNumber = tokens[2];
You can try using split using the '_' delimiter.
The String.split methods splits this string around matches of the given ;parameter. So use like this
String[] output = input.split("_");
here output[1] will be your desired result
ANd input will be like
String input = "xs_1234323_00_32"
I would do this:
filename.split("_", 3)[1]
The second argument of split indicates the maximum number of pieces the string should be split into, in your case you only need 3. This will be faster than using the single-argument version of split, which will continue splitting on the delimiter unnecessarily.
I'm trying to split some user input. The input is of the form a1 b2 c3 d4.
For each input (eg; a1), how do I split it into 'a' and '1'?
I'm familiar with the string split function, but what do I specify as the delimiter or is this even possible?
Thanks.
You could use String#substring()
String a1 = "a1"
String firstLetterStr = a1.substring(0,1);
String secondLetterStr = a1.substirng(1,a1.length());
Similarly,
String c31 = "c31"
String firstLetterStr = c31.substring(0,1);
String secondLetterStr = c31.substirng(1,c31.length());
If you want to split the string generically (rather than trying to count characters per the other answers), you can still use String.split(), but you have to utilize regular expressions. (Note: This answer will work when you have strings like a1, a2, aaa333, etc.)
String ALPHA = "\p{Alpha}";
String NUMERIC = "\d";
String test1 = "a1";
String test2 = "aa22";
ArrayList<String> alpha = new ArrayList();
ArrayList<String> numeric = new ArrayList();
alpha.add(test1.split(ALPHA));
numeric.add(test1.split(NUMERIC));
alpha.add(test2.split(ALPHA));
numeric.add(test2.split(NUMERIC));
At this point, the alpha array will have the alpha parts of your strings and the numeric array will have the numeric parts. (Note: I didn't actually compile this to test that it would work, but it should give you the basic idea.)
it really depends how you're going to use the data afterwards, but besides split("") or accessing individual characters by index, one other way to split into individual character is toCharArray() -- which just breaks the string into an array of characters...
Yes, it is possible, you can use split("");
After you split user input into individual tokens using split(" "), you can split each token into characters using split("") (using the empty string as the delimiter).
Split on space into an array of Strings, then pull the individual characters with String.charAt(0) and String.charAt(1)
I would recommend just iterating over the characters in threes.
for(int i = 0; i < str.length(); i += 3) {
char theLetter = str.charAt(i);
char theNumber = str.charAt(i + 1);
// Do something
}
Edit: if it can be more than one letter or digit, use regular expressions:
([a-z]+)(\d+)
Information: http://www.regular-expressions.info/java.html