[英]Replacing a character with other in java
亲爱的stackoverflow成员,我有一个小问题,
我想用Java中的其他字符替换字符串中的某些字符,执行此操作的代码如下,
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1.removeAllItems();
String str = new GenericResource_JerseyClient().getlist();
String [] temp = null;
temp = str.split(",");
temp[1]=temp[1].replaceAll("'", "");
temp[1]=temp[1].replaceAll(" ", "");
temp[1]=temp[1].replace("[", "");
temp[1]=temp[1].replace("]", "");
for(int i =0; i < temp.length ; i++)
{
jComboBox1.addItem(temp[i]);
} // TODO add your handling code here: // TODO add your handling code here:
// TODO add your handling code here
}
从上面的代码可以看出,我将“'”,“ [[“,”]”和空白全部替换为空。 从代码中还可以看出,我将字符串分为两部分。 在after后面的字符串部分中,代码可以正常工作,但是在before之前的字符串部分中,代码似乎无法正常工作。 我还附加了客户端输出的下拉列表的副本。
非常感谢您提供有关如何从字符串中删除[和'的任何帮助。
干杯。
您只在temp[1]
上执行替换-而问题似乎出在下拉列表中显示的第一项中,这大概是temp[0]
的数据。
我怀疑您应该将删除代码提取到单独的方法中,然后在循环中调用它:
for(int i =0; i < temp.length ; i++)
{
jComboBox1.addItem(removeUnwantedCharacters(temp[i]));
}
另外,我强烈建议您在不需要显式匹配正则表达式模式的情况下使用replace
而不是replaceAll
。 具有以下代码可能会非常令人困惑:
foo = foo.replaceAll(".", "");
看起来好像要删除点,但实际上会删除所有字符,例如“。”。 被视为正则表达式...
在分割字符串之前,请执行所有替换操作。 这比在循环中执行相同的代码更好。
例如:
String cleanString = str.replace("'", "").replace(" ", "").replace("[", "").replace("]", "");
String[] temp = cleanString.split(",");
for(int i = 0; i < temp.length ; i++) {
jComboBox1.addItem(temp[i]);
}
好吧,您只能在索引为1(第二个索引)的项目中执行替换。 但是,然后将所有这些添加到组合中(实际上是两个)。 尝试:
for(int i =0; i < temp.length ; i++){
temp[i]=temp[i].replaceAll("'", "");
temp[i]=temp[i].replaceAll(" ", "");
temp[i]=temp[i].replace("[", "");
temp[i]=temp[i].replace("]", "");
}
常见问题。
我认为这段代码符合您的要求。
您仅在temp [1](它是字符串的第二部分)上进行替换。 您还需要在temp [0]中进行。 最好创建一个接受字符串并进行替换并在temp [0]和temp [1]上调用的函数。 您还可以考虑使用正则表达式一次替换所有字符,而不是一次替换一次。
String [] temp = String.split(",")
for (int i = 0;i<temp.length;i++) {
temp[i] = replaceSpecialChars(temp[i]);
}
public String replaceSpecialChars(String input) {
// add your replacement logic here
return input
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.