找到特殊字符后删除字符

时间:2012-08-01 04:18:11

标签: jsp

我正在使用jsp进行基于Web的项目。我想删除'@'之后的所有字符,包括'@'。

假设我将“stackoverflow@stack.com”作为用户的输入。我必须删除@之后的字符以及'@'即

o/p is stackoverflow

我认为一种方法是使用java数组或regex。 请建议我解决这个问题的更好方法。有没有其他方法可以解决这个问题?

我怎样才能使用JSP?我不能只为jsp使用javascript。

谢谢。

1 个答案:

答案 0 :(得分:0)

为什么不使用Java String?

一种方式:

String output = input;
int at = input.indexOf('@');
if (at != -1) {
    output = input.substring(0, at); 
}

(它可以优化为更少的行,但这是编写它的最清晰的方法)。

或者

String output = input.split("@", 2)[0];
// I prefer the first way, this is a bit more wasteful, but that is probably
// just a personal hang up from the days of embedded C ;-)
相关问题