我需要做一个字符串操作。最初,我将获得一个图像路径,如下所示:
image = images/registration/student.gif
image = images/registration/student_selected.gif
image = images/registration/student_highlighted.gif我需要操作字符串图像路径来获得两个不同的图像路径。
一种是通过如下方式获取路径:
image1 = images/registration/student.gif为此,我使用了以下函数:
private String getImage1(final String image) {
String image1 = image;
image1 = image.replace("_highlight", "");
image1 = image.replace("_selected", "");
return image1;
}我需要的第二个镜像路径是获取路径:
image2 = image = images/registration/student_selected.gif我用来获取image2输出的函数是:
private String getImage2(final String image) {
String image2 = image;
boolean hasUndersore = image2.matches("_");
if (hasUndersore) {
image2 = image2.replace("highlight", "selected");
} else {
String[] words = image2.split("\\.");
image2 = words[0].concat("_selected.") + words[1];
}
return image2;
}但是上面的方法并没有给我预期的结果。有人能帮我吗?非常感谢!
发布于 2012-06-27 19:53:27
您可以使用indexOf(...)而不是match()。match将根据正则表达式检查整个字符串。
for (final String image : new String[] { "images/registration/student.gif", "images/registration/student_highlight.gif",
"images/registration/student_selected.gif" }) {
String image2 = image;
final boolean hasUndersore = image2.indexOf("_") > 0;
if (hasUndersore) {
image2 = image2.replaceAll("_highlight(\\.[^\\.]+)$", "_selected$1");
} else {
final String[] words = image2.split("\\.");
image2 = words[0].concat("_selected.") + words[1];
}
System.out.println(image2);
}这将为您提供预期的输出。
顺便说一句,我更改了replaceAll(..)正则表达式,因为图像文件名也可以有字符串"highlight“。例如stuhighlight_highlight.jpg
发布于 2012-06-27 20:08:20
如果我理解正确的话,您需要以下来自各个函数的输出
"images/registration/student.gif"-> getImage1(String)
"images/registration/student_selected.gif" -> getImage2(String)假设上面的输出,两个函数getImage1()->中几乎没有错误
在第二个替换中,您需要使用image1变量,该变量是第一个替换的输出。
getImage2()->
我已经修改了下面的函数,它提供了所需的输出
private static String getImage1(final String image) {
return image.replace("_highlighted", "").replace("_selected", "");
}
private static String getImage2(final String image) {
if (image.indexOf("_")!=-1) {
return image.replace("highlighted", "selected");
} else {
return image.replace(".", "_selected.");
}
}发布于 2012-06-27 19:58:19
首先,getImage1()可能没有执行您希望它执行的操作。您为变量image1赋值3次。显然,返回最后一个赋值。
其次,image2.matches("_")不会告诉您image2是否包含下划线(我认为这就是您在这里要做的事情)。
我建议先自己做一些测试/调试。
https://stackoverflow.com/questions/11225331
复制相似问题