<tag k="addr:street" v="St. Croix gate"/>
public void map(Object key, Text value, Context context
) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
String cb = itr.nextToken();
if(cb.contains("k=\"addr:street\"")){
String roadName = itr.nextToken();
while(!roadName.contains("\"/>")) {
roadName = roadName + itr.nextToken();
}
word.set(roadName);
context.write(word, one);
}
}
}
}
正如你所看到的,我试图在 v="St. Croix Gate"/> 中获取字符串,但由于 Tokenizer 为每个空格添加了一个新的标记,所以我只得到输出“gate”
最佳答案
这对我有用:
String element = "<tag k=\"addr:street\" v=\"St. Croix gate\"/>";
String searchAtt = "v";
StringTokenizer itr = new StringTokenizer(element);
while (itr.hasMoreTokens()) {
// split by '='
String s = itr.nextToken("=");
// is splited by '=' so the last word is the attribute name
if (s.endsWith(searchAtt)) {
// next token is '=' then comes the value of the attribute
// split it by \"
itr.nextToken("\"");
// next token will be the content
String content = itr.nextToken();
System.out.println("Searched attribute: " + content);
}
}
关于java - 如何使用 StringTokenizer 获取字符串中的特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58218390/