[英]How to pull out sub-string from string (Android)?
I'm trying to pull out sub-string from a string using java.Util.Scan
我正在尝试使用
java.Util.Scan
从字符串中提取子字符串
The sub-string is between " <TD class=MoreB align=center>
" and " </TD>
" in the original string 子字符串在原始字符串的“
<TD class=MoreB align=center>
”和“ </TD>
”之间
This is the code: 这是代码:
public static String pullStringOut(String str)
{
String stringer = null;
Scanner scanner = new Scanner(str);
scanner.findInLine("<TD class=MoreB align=center>");
while (scanner.hasNext() && scanner.next() != "</TD>")
{
stringer+= " " + (scanner.next());
}
return stringer;
}
but it's not working well. 但效果不佳。
From the original string: 从原始字符串:
" <TD class=MoreB align=center>TextTextTextText</TD></TR></TABLE> }
" “
<TD class=MoreB align=center>TextTextTextText</TD></TR></TABLE> }
”
I get the following result: 我得到以下结果:
"
TextTextTextText</TD></TR></TABLE> }
"“
TextTextTextText</TD></TR></TABLE> }
”
Instead of the expected 而不是预期的
"TextTextTextText"
“ TextTextTextText”
A few problems: 一些问题:
scanner.next() != "</TD>"
will always be true
as the operands will not be the same object. scanner.next() != "</TD>"
将始终为true
因为操作数将不是同一对象。 Use !scanner.next().equals("</TD>")
. 使用
!scanner.next().equals("</TD>")
。 From Reference Equality Operators == and != section of the JLS : 从JLS的参考相等运算符==和!=部分 :
The result of != is false if the operand values are both null or both refer to the same object or array;
如果操作数值都为null或都引用相同的对象或数组,则!=的结果为false;否则,结果为false。 otherwise, the result is true.
否则,结果为true。
scanner.next()
is being called twice on each iteration of the loop. 在循环的每次迭代中,
scanner.next()
都会被调用两次。 Change to: 改成:
String line; while (scanner.hasNext() && !(line = scanner.next()).equals("</TD>")) { stringer+= " " + line; }
You can use a Regex Expresssion. 您可以使用正则表达式。
Something like : 就像是 :
Pattern p = Pattern.compile("/\<TD class=MoreB align=center>(.*)\<\/td\>/");
Matcher m = p.matcher(str);
while(m.find()) {
//do whatever you want here
}
(not tested) (未测试)
Here is an alternate solution: 这是一个替代解决方案:
String tvt ="<TD class=MoreB align=center>TextTextTextText</TD></TR></TABLE> }" //your original string
String s ="<TD class=MoreB align=center>";
String f= "</TD>";
int sindex =tvt.indexOf(s);
int findex =tvt.indexOf(f);
String fs = "";
if(sindex!=-1 && findex!=-1)
fs=tvt.substring(sindex+s.length(), findex); // your desired substring
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.