开发者

Generic trim function in java?

i have a requirement, where i need to develop a single method which accepts any type of paramter(String or Integer etc) and applies tri开发者_开发技巧m() to remove leading and trialing spaces. please help me how to write generic method to achieve this?

Thanks!


Java has strictly defined types, it's not PHP or Javascript. Integer does not have spaces. Simply use trim() method of String object. If your 'integer' is actually a string, do (String.valueOf(x)).trim()


It does not make a lot of sense, but here it goes:

public String trim(Object o) {
  if (o != null) { 
    return o.toString().trim();
  }
  return null;
}


if an integer is like 12345---. --- indicates 3 spaces. how can i remove? do i need to convert it to string before trimming?

If an 'integer' has trailing spaces, it is already the string representation of the integer, not the integer itself. Therefore:

String i = "12345   ";
String trimmed = i.trim();

By contrast, the following is simply not legal

int i = "12345   ";  // compilation error

and a string representation of an integer produced like this:

String i = String.valueOf(12345);

will not have leading or trailing whitespace.


In java, all objects have .toString() method which returns string representation of that object.

You can then call .trim() method on that string, so your function may look like this:

public static String trimAny(Object o) {
    return o.toString().trim();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜