从上一个索引中删除字符串中的特定字符

时间:2013-08-22 09:07:40

标签: java

如果从最后一个索引中删除字符串中的特定字符',',如果存在。是否可以删除?

String str="update employee set name='david', where id=?";

6 个答案:

答案 0 :(得分:1)

试试这个:

int index = str.length() - 2;  //Calculating the index of the 2nd last element
str = str.subString(0,index);  //This shall give you the string without the last element

或者如果你想删除像“,”这样的特定字符:

str.replace(",","");

您还可以使用indexOf()方法(或lastIndexOf()方法)查找索引并创建两个子字符串,然后合并子字符串。 或者,您可以根据字符拆分字符串并合并分割的字符串..

答案 1 :(得分:0)

来自 Apache Common-lang StringUtils

的合适解决方案
StringUtils#removeEnd(String str, String remove)
StringUtils#removeEndIgnoreCase(String str, String remove)
仅当

removeEnd方法位于源字符串的末尾时,才会删除子字符串。而removeEndIgnoreCase对案例不敏感也是如此。

答案 2 :(得分:0)

尝试StringUtils.removeEnd

String str="update employee set name='david', where id=?";
        System.out.println(""+StringUtils.removeEnd(str, REMOVABLE_CHAR));

答案 3 :(得分:0)

可能是这样的:

String str="update employee set name='david', where id=?";    
int i = str.lastIndexOf(",");
if(i > -1) {
    String newStr = str.subSequence(0, i-1).toString() + str.subSequence(i+1, str.length()-1).toString();
}

答案 4 :(得分:0)

如果要检查字符串中的最后一个字符,如果它是','字符则删除它,以下内容应该有效。

String str="update employee set name='david', where id=?,";    

if(str.lastIndexOf(',') == str.length()-1){
    str = str.substring(0, str.length()-1);
}
System.out.println(str);

此if语句检查最后一个','是否与字符串中的最后一个字符处于同一索引(即它是字符串中的最后一个字符)。如果是这样,它将删除最后一个字符并打印新字符串。

输入:update employee set name='david', where id=?,
输出:update employee set name='david', where id=?

输入:update employee set name='david', where id=?
输出:update employee set name='david', where id=?

答案 5 :(得分:0)

如果您使用的逻辑类似于:

Map<String, Object> values --> populated with what you have to update
String update = "update employee set ";
for (String key : values.keySet())
{
    update = update + key + "=" + values.get(key) + ",";
}

update = update + " where id = ?";

我建议您更改for循环,如下所示,您不必进行任何类型的字符删除。

String update = "update employee set ";
String add = "";
for (String key : values.keySet())
{
    update = update + add + key + "=" + values.get(key);
    add = ", ";
}

update = update + " where id = ?";