2013-08-22 50 views
0

如果存在,如何从上一个索引中的字符串中删除特定字符','是否可以删除?从Apache的普通琅StringUtils从上一个索引中删除字符串中的特定字符

StringUtils#removeEnd(String str, String remove) 
StringUtils#removeEndIgnoreCase(String str, String remove) 

removeEnd方法

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

什么是您的预期输入,预期输出和您尝试过什么? – Joni

+0

您的预期投入是多少? –

+1

Joni在(部分)中得到的是*“如何从最后一个字符串中删除特定字符”*是不正确的英语......并且我们不知道您*实际*的含义。 (你会发现人们猜测你的意思是......在他们的答案中。) –

回答

0

合适的溶液去除,只有当它是在源串的端部的子串。而removeEndIgnoreCase与大小写不敏感相同。

0

尝试StringUtils.removeEnd

String str="update employee set name='david', where id=?"; 
     System.out.println(""+StringUtils.removeEnd(str, REMOVABLE_CHAR)); 
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(); 
} 
+0

它会失败,如果'?,找不到,该怎么办? – user2680017

+0

我想删除','不是'?' – user2680017

+0

@ user2680017那么,如果找不到给定的字符串,lastIndexOf将返回-1。我将编辑上面的代码。只要改变? to,或任何字符串u prever – Oli

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()方法)查找索引并创建两个子字符串,然后合并子字符串。 或者,可以根据字符拆分字符串并合并分裂的字符串..

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=?

+0

我想删除','。如果在字符串中找到,也是从上次开始。 – user2680017

+0

如果它是字符串中倒数第二个字符,您希望从字符串中删除','?否则,让字符串保持原样? – leigero

+0

你可以编辑你的问题,并添加字符串与','在它和预期的输出? – leigero

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 = ?"; 
相关问题