在Java中,我需要在String中找到所有出现的String。
例如
String myString;
myString = "Random_XML_Stuff_Here <tag k="name" v="Example Road"/>
More_Random_XML_Stuff <tag k="name" v="Another name"/> More_XML_Stuff" Etc...
所以我需要能够抓住所有道路名称的内容。在第一个例子中,我需要能够将String设置为“Example Road”。
伪码:
String streets = "";
while(more occurrences of street names exist)
{
streets = streets + "," + (street.occurrence of street name);
}
在上面的示例中,字符串的内容为“Example Road,Another name”。
答案 0 :(得分:1)
您可以使用类似String[] parseValue(String)
函数
public static String[] parseValue(String in) {
String openTag = "<tag k=\"name\" v=\"";
int p1 = in.indexOf(openTag);
java.util.List<String> al = new java.util.ArrayList<String>();
while (p1 > -1) {
int p2 = in.indexOf("\"/>", p1 + 1);
if (p2 > -1) {
al.add(in.substring(p1 + openTag.length(), p2));
} else {
break;
}
p1 = in.indexOf(openTag, p2 + 1);
}
String[] out = new String[al.size()];
return al.toArray(out);
}
public static void main(String[] args) {
String myString = "Random_XML_Stuff_Here <tag k=\"name\" v=\"Example Road\"/> "
+ "More_Random_XML_Stuff <tag k=\"name\" v=\"Another name\"/>";
System.out.println(java.util.Arrays
.toString(parseValue(myString)));
}
输出
[Example Road, Another name]
答案 1 :(得分:1)
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class welcome {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String text = "Random_XML_Stuff_Here <tag k=\"name\" v=\"Example Road\"/> More_Random_XML_Stuff <tag k=\"name\" v=\"Another name\"/> More_XML_Stuff";
String road_string = GetRoadString(text);
System.out.println(road_string);
}
static String GetRoadString(String text)
{
Pattern pattern = Pattern.compile("<tag\\s+k=\"name\"\\s+v=\"(.*?)\"/>");
Matcher matcher = pattern.matcher(text);
// using Matcher find(), group(), start() and end() methods
String road_string = "";
while (matcher.find()) {
road_string = road_string + matcher.group(1)+ ",";
}
return road_string.substring(0, road_string.length()-1);
}
}
enter code here
答案 2 :(得分:0)
由于您拥有固定的XML格式,因此您可以使用正则表达式匹配来查找所提到的道路名称。
Pattern roadNamePattern = Pattern.compile("v=\"(.*?)\"/>");
Matcher matcher = roadNamePattern.matcher(xmlString);
while (matcher.find()) {
String roadName = matcher.group(1);
}
答案 3 :(得分:0)
使用python回答以下问题:
在字符串中找到所有出现的字符,例如:
I / P str =&#39; aababbdf&#39;
O / P:[(&#39; a&#39;,2),(&#39; b&#39;,1),(&#39; a&#39;,1),(&#39; b& #39;,2),(&#39; d&#39;,1),(&#39; f&#39;,1)]
i=j=total=0;
data=[];
for i in range (0,len(str)):
count=0;
i = j;
if( total != len(str)):
for j in range (i,len(str)):
if str[i] == str[j]:
count=count+1;
total = total +1;
char=str[i];
else:
break;
data.append((char,count));
print("\n data",data);