How to remove first and last character of a string?

匿名 (未验证) 提交于 2019-12-03 02:49:01

问题:

I have worked in SOAP message to get LoginToken from Webservice, and store the LoginToken in String and used System.out.println(LoginToken); to print. This prints [wdsd34svdf], but I want only wdsd34svdf so, how to remove square bracket. please any one help me.

Thanks

Example:

String LoginToken=getName().toString(); System.out.println("LoginToken" + LoginToken); 

Output: [wdsd34svdf] I want wdsd34svdf

回答1:

It's easy, You need to find index of [ and ] then substring. (Here [ is always at start and ] is at end) ,

String loginToken="[wdsd34svdf]"; System.out.println(loginToken.substring(1, loginToken.length()-1)); 


回答2:

You can always use substring:

String loginToken = getName().toString(); loginToken = loginToken.substring(1, loginToken.length() - 1); 


回答3:

This is generic solution:

str.replaceAll("^.|.$", "") 


回答4:

Another solution for this issue is use commons-lang (since version 2.0) StringUtils.substringBetween(String str, String open, String close) method. Main advantage is that it's null safe operation.

StringUtils.substringBetween("[wdsd34svdf]", "[", "]"); // returns wdsd34svdf



回答5:

I had a similar scenario, and I thought that something like

str.replaceAll("\[|\]", ""); 

looked cleaner. Of course, if your token might have brackets in it, that wouldn't work.



回答6:

This way you can remove 1 leading "[" and 1 trailing "]" character. If your string happen to not start with "[" or end with "]" it won't remove anything:

str.replaceAll("^\\[|\\]$", "") 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!