如何删除字符串的第一个和最后一个字符?

我在 SOAP 消息中工作,以便从 Webservice 获取 LoginToken,并将其存储为 String。U 使用 System.out.println(LoginToken);打印值。这打印 [wdsd34svdf],但我只要 wdsd34svdf。如何删除输出开始和结束处的这些方括号?

例如:

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

输出是: [wdsd34svdf]

我只要 wdsd34svdf

240491 次浏览

You can always use substring:

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

You need to find the 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 ) );

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.

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

This is generic solution:

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

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("^\\[|\\]$", "")

StringUtils's removeStart and removeEnd method help to remove string from start and end of a string.

In this case we could also use combination of this two method

String string = "[wdsd34svdf]";
System.out.println(StringUtils.removeStart(StringUtils.removeEnd(string, "]"), "["));

This will gives you basic idea

    String str="";
String str1="";
Scanner S=new Scanner(System.in);
System.out.println("Enter the string");
str=S.nextLine();
int length=str.length();
for(int i=0;i<length;i++)
{
str1=str.substring(1, length-1);
}
System.out.println(str1);

this is perfectly working fine

String str = "[wdsd34svdf]";
//String str1 = str.replace("[","").replace("]", "");
String str1 = str.replaceAll("[^a-zA-Z0-9]", "");
System.out.println(str1);




String strr = "[wdsd(340) svdf]";
String strr1 = str.replaceAll("[^a-zA-Z0-9]", "");
System.out.println(strr1);

SOLUTION 1

def spaceMeOut(str1):


print(str1[1:len(str1)-1])


str1='Hello'


print(spaceMeOut(str1))

SOLUTION 2

def spaceMeOut(str1):


res=str1[1:len(str1)-1]


print('{}'.format(res))


str1='Hello'


print(spaceMeOut(str1))

In Kotlin

private fun removeLastChar(str: String?): String? {
return if (str == null || str.isEmpty()) str else str.substring(0, str.length - 1)
}

Try this to remove the first and last bracket of string ex.[1,2,3]

String s =str.replaceAll("[", "").replaceAll("]", "");

Exptected result = 1,2,3