How to remove first and last character of a string?

后端 未结 12 2069
遥遥无期
遥遥无期 2020-12-08 08:56

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 prin

相关标签:
12条回答
  • 2020-12-08 09:21

    You can always use substring:

    String loginToken = getName().toString();
    loginToken = loginToken.substring(1, loginToken.length() - 1);
    
    0 讨论(0)
  • 2020-12-08 09:23

    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

    0 讨论(0)
  • 2020-12-08 09:30

    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))

    0 讨论(0)
  • 2020-12-08 09:30

    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);
    
    0 讨论(0)
  • 2020-12-08 09:34

    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.

    0 讨论(0)
  • 2020-12-08 09:39

    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("^\\[|\\]$", "")
    
    0 讨论(0)
提交回复
热议问题