I have been trying to get a number from a html string, but I cannot come up with a way to do it properly, I already looked for instructions for Jsoup, but I don't really understand how it works.
This is one of the strings I have to parse:
<span class="b">014:</span>
What I'm trying to get as output is 014, the name of the link. I need to get the number in a String variable, not Integer by the way.
Or this
<span class="b">08:</span>
For the 08.
The main problem I'm finding is that two things change in the string, the number after /paline/percorso/ and the number which is the name of the link. Could someone please help me?
If all your samples are like this, you can do this with simple string functions:
final String input = "<span class=\"b\">014:</span>";
final int i2 = input.lastIndexOf( "</a>" );
final int i1 = input.lastIndexOf( '>', i2 ) + 1;
final String result = input.substring( i1, i2 );
System.out.println( result );
I'd probably try a simple regex. Although depending on your string, it may be more complex than a simple quick and dirty regex.
String html = "<span class="b">014:</span>"
html.replaceAll( ".*<a.*>([0-9]*)</a.*", "$1" );
You can try something like:
Elements resultLinks = doc.select("span.b > a");
for (Element e:resultLinks)
String yourText=e.text();
Related
I was just wondering if there was a way to replace strings with variables. Specifically through the methods replaceAll("", ""). Wondering if its possible to do something like :
int i = 2;
replaceAll("\\D", i);
If not, is there a roundabout way to do this?
You can only replace parts of Strings with a String.
String text = "Hello World";
int i = 2;
text = text.replaceAll("o", ""+i);
String#replaceAll(x,x) only accepts a String as its second parameter. The solution here is to convert your int into a String:
myString.replaceAll("\\D", String.valueOf(i));
use this:
int i = 2;
replaceAll("\\D", ""+i);
yes it is. As you assume you can use
s = s.replaceAll("textToReplace",Integer.toString(i));
to replace all the occurrences of textToReplace in the String s.
I have code like this :
int [] arrayOfImages = new int[namesOfSubjectsColorCode.size()];
int y = 0;
for (int x = 0 ; x<namesOfSubjectsColorCode.size();x++) {
nameOfColorCode = namesOfSubjectsColorCode.get(x);
String str = "com" + "." + "nyurals" + "." + "R" + "." + "drawable" + "." + nameOfColorCode;
arrayOfImages[y] = Integer.parseInt(str);
// Integer.parseInt(str);
y++;
}
Here, I have created integer array. Then, I have created string and by using Integer.parseInt() I want to convert it to int so that, my array of integer should generate dynamically. It is giving NumberFormatException.
Please suggest to me a solution for this.
There is no way for this String to be reasonably turned into an int.
String str = "com" + "." + "nyurals" + "." + "R" + "." + "drawable" + "." + nameOfColorCode;
Something like this would be expected:
String str = "1";
Its obvious that it gives you NumberFormatException. Look at your code :
Your str variable contains String which cant parse into Integer value.
Argument for Integer.parseInt() is invalid, you can't pass it string like "com.nyurals.." etc
From the docs:
public static int parseInt(String s)
throws NumberFormatException
Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.
And that's exactly what you're getting: NumberFormatException.
EDIT:
You probably want to do something like this:
nameOfColorCode = namesOfSubjectsColorCode.get(x);
String str = "" + nameOfColorCode;
int resourceId = this.getResources().getIdentifier(str, "drawable", this.getPackageName());
arrayOfImages[y] = resourceId;
y++;
If you want to get the int (id) of a resource than you should use
Resources res = activity.getResources();
res.getIdentifier("name","resourceType",activty.getPackageName());
change the name with actual name and resourceType with actual resource type (drawable,color,etc);
As others wrote you don't have an int in your string, it's just an int and not a reference to resoruce
You can access the constants you're trying to reference via http://docs.oracle.com/javase/tutorial/reflect/ but you really don't want to do that.
You'd be better served putting the int's in some form of map of which you can then select some kind of subset dependent on changing information
Integer.parseInt() expects to be given an integer of some sort, not a string of the format com.nyurals.R.drawable.<<nameOfColorCode>>.
Generally, in Android, you would access the variables directly with something like:
R.drawable.SomeName
rather than trying to decode (or, in your case, directly using) the string to get a value.
For example, the following code gets the surface view based on an ID:
SurfaceView sv = (SurfaceView)findViewById(R.id.PfrRightAntiView);
If you do need to dynamically extract a resource based on a string known only at runtime, look into Resources.getIdentifier(), an example of which can be found here.
As per this article, that method may not be the fastest. It may be better to use the reflection method as shown in that link.
May your str returns null so Integer.parseInt(null) return number format exception
I have an string str of unknown length (but not null) and a given maximum length len, this has to fit in. All I want to do, is to cut the string at len.
I know that I can use
str.substring(0, Math.min(len, str.length()));
but this does not come handy, if I try to write stacked code like this
code = str.replace(" ", "").left(len)
I know that I can write my own function but I would prefer an existing solution. Is there an existing left()-function in Java?
There's nothing built in, but Apache commons has the StringUtils class which has a suitable left function for you.
If you don't want to add the StringUtils Library you can still use it the way you want like so:
String string = (string.lastIndexOf(",") > -1 )?string.substring(0, string.lastIndexOf(",")): string;
Use Split.
String str = "Result string Delimiter Right String";
System.out.println(str.split("Delimiter")[0].trim());
Output: "Result string"
No there is not left() in the String class, as you can refer API. But as #Mark said Apache StringUtils has several methods: leftPad(), rightPad(), center() and repeat(). You can also check
this:http://www.jdocs.com/lang/2.1/org/apache/commons/lang/StringUtils.html
You can use String Format
In this example the format specifier "%-9s" means minimum 9 characters left justified (-).
"%-9.9s" means maximum 9 characters.
System.out.println (String.format("%-9.9s","1234"));
System.out.println (String.format("%-9.9s","123456789ABCD"));
int len=9;
System.out.println (String.format("%-"+len+"."+len+"s","123456789ABCD"));
Prints:
1234
123456789
123456789
in OP's case it would be something like this:
static final int MAXLEN=9;
code = String.format("%-"+MAXLEN+"."+MAXLEN+"s",str.replace(" ", ""));
put the below function in a class:
public static String getLeftString(String st,int length){
int stringlength=st.length();
if(stringlength<=length){
return st;
}
return st.substring((stringlength-length));
}
in my case I want to get date only.
String s = "date:2021-01-01";
int n = s.length() - 10; //10 was the length of the date
String result = s.substring(n);
the result will be "2021-01-01";
I'm moving some code from objective-c to java. The project is an XML/HTML Parser. In objective c I pretty much only use the scanUpToString("mystring"); method.
I looked at the Java Scanner class, but it breaks everything into tokens. I don't want that. I just want to be able to scan up to occurrences of substrings and keep track of the scanners current location in the overall string.
Any help would be great thanks!
EDIT
to be more specific. I don't want Scanner to tokenize.
String test = "<title balh> blah <title> blah>";
Scanner feedScanner = new Scanner(test);
String title = "<title";
String a = feedScanner.next(title);
String b = feedScanner.next(title);
In the above code I'd like feedScanner.next(title); to scan up to the end of the next occurrence of "<title"
What actually happens is the first time feeScanner.next is called it works since the default delimiter is whitespace, however, the second time it is called it fails (for my purposes).
You can achieve this with String class (Java.lang.String).
First get the first index of your substring.
int first_occurence= string.indexOf(substring);
Then iterate over entire string and get the next value of substrings
int next_index=indexOf( str,fromIndex);
If you want to save the values, add them to the wrapper class and the add to a arraylist object.
This really is easier by just using String's methodsdirectly:
String test = "<title balh> blah <title> blah>";
String target = "<title";
int index = 0;
index = test.indexOf( target, index ) + target.length();
// Index is now 6 (the space b/w "<title" and "blah"
index = test.indexOf( target, index ) + target.length();
// Index is now at the ">" in "<title> blah"
Depending on what you want to actually do besides walk through the string, different approaches might be better/worse. E.g. if you want to get the blah> blah string between the <title's, a Scanner is convenient:
String test = "<title balh> blah <title> blah>";
Scanner scan = new Scanner(test);
scan.useDelimiter("<title");
String stuff = scan.next(); // gets " blah> blah ";
Maybe String.split is something for you?
s = "The almighty String is mystring is your String is our mystring-object - isn't it?";
parts = s.split ("mystring");
Result:
Array("The almighty String is ", " is your String is our ", -object - isn't it?)
You know that in between your "mystring" must be. I'm not sure for start and end, so maybe you need some s.startsWith ("mystring") / s.endsWith.
This question is rather difficult to confer, for simplistic sake:
I am loading some Strings via XML (XStream).
for example, Your total count is +variable+ .
The outcome would be
"Your total count is +variable+ ."
when it ideally should be
"Your total count is" + variable + "." aka "Your total count is 1."
The issue: (if you can't see it) it reads the variable as if it were a String.
I know I would need to split that String from where the plus sign starts and ends and then connect it to the String, for it to read as a variable, like the above. But how? I need this to be done so that the String before the variable and after it is split.
so:
"Your total count is 50, would you like a cookie?"
aka
"Your total count is " + variable + " , would you like a cookie?"
Thank you alot!
Okay, I agree it's very confusing. I've edited this post (read below).
Well I am loading some Strings via XML this could be the same case if I were loading them via a .txt or a config file.
On the XML file, I lay it out like so:
<list>
<dialogue>
<line>
<string> Your total count is + Somewhere.totalCount +, Would you like a cookie?</string>
</line>
</dialogue>
</list>
As you can see, the XML file can't locate where the variable (in a class is), nor can it recognise if it is a variable or a string.
I know that I would need to alter the way it reads it, so if there is a plus sign (+) anywhere on the String, it would simply "split" it away from the original String so I can reconnect it.
E.g. Your phone number is + PhoneBook.phoneNumber + should I call you? as it would be read from a XML file.
I want to "split" the String from front to back like so:
"Your phone number is " + PhoneBook.phoneNumber + " should I call you?"
At the same time, I'm not assigning a variable because It's already declared in the XML file, I want it to recognise it as a int.
First, Java can not know that the +variable+ part of your string should be replaced with the value of the corresponding variable and also does not provide some "eval" like functionality like PHP or other scripting languages do, which might help you with that.
If you want to exactly replace this specific '+variable+' part of the string, it can be done like this:
int variable = 1;
String text = "Your total count is +variable+.";
String textWithVariableValue = text.replaceAll("\\+variable\\+", Integer.toString(variable));
But if you want to replace variables with arbitrary names, you will have to put them into a Map first, and then find all occurences of +somename+ in the string and replace it with the corresponding value stored in the map. Something like this:
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("var1", 1);
variables.put("foo", 5);
String text = "var1 = +var1+, foo = +foo+";
String textWithVariableValues = text;
for (String variableName : variables.keySet()) {
Object variableValue = variables.get(variableName);
textWithVariableValues = textWithVariableValues.replaceAll("\\+" + variableName + "\\+", variableValue.toString());
}
Sounds like what you need is the
String.format() method:
int total = calculateTotal();
String s = String.format("Your total is %1d.", total);
Not split, but find and replace.
Simplistically,
int variable = 1;
String src = "Your total count is +variable+.";
String result = src.replaceAll("\\+variable\\+.", Integer.toString(variable));
System.out.println(result);
Should print "Your total count is 1."
EDIT: (after your comment) If you need to replace a multiple variables in one go then the following works for me:
// Replace the ff. with the actual map of variables & values
Map<String, String> vars = Collections.singletonMap(
"variable", Integer.toString(123));
String src = "Your total count is +variable+.";
Pattern p = Pattern.compile("\\+(\\w+)\\+");
StringBuffer sb = new StringBuffer();
Matcher m = p.matcher(src);
while (m.find()) {
String varName = m.group(1);
if (vars.containsKey(varName)) {
m.appendReplacement(sb, vars.get(varName));
}
}
m.appendTail(sb);
System.out.println(sb.toString());
Prints "Your total count is 123."