【问题标题】:How to split String before first comma?如何在第一个逗号之前拆分字符串?
【发布时间】:2015-08-15 18:23:03
【问题描述】:

我有一个使用 String 的重写方法,它以以下格式返回 String:

 "abc,cde,def,fgh"

我想把字符串内容分成两部分:

  1. 第一个逗号和之前的字符串

  2. 第一个逗号后的字符串

我的重写方法是:

@Override
protected void onPostExecute(String addressText) {

    placeTitle.setText(addressText);
}

现在如何将字符串分成两部分,以便我可以使用它们将文本设置为两个不同的TextView

【问题讨论】:

    标签: java string delimiter


    【解决方案1】:

    你可以使用下面的代码sn -p

    String str ="abc,cde,def,fgh";
    String kept = str.substring( 0, str.indexOf(","));
    String remainder = str.substring(str.indexOf(",")+1, str.length());
    

    【讨论】:

    • 我觉得这是最好的答案,因为您可以将它放在一行中。谢谢
    • 但是如果它没有找到任何逗号那么它会崩溃为错误-----java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    【解决方案2】:
    public static int[] **stringToInt**(String inp,int n)
    {
    **int a[]=new int[n];**
    int i=0;
    for(i=0;i<n;i++)
    {
        if(inp.indexOf(",")==-1)
        {
            a[i]=Integer.parseInt(inp);
            break;
        }
        else
        {
            a[i]=Integer.parseInt(inp.substring(0, inp.indexOf(",")));
            inp=inp.substring(inp.indexOf(",")+1,inp.length());
        }
    }
    return a;
    }
    

    我创建了这个函数。参数是input string (String inp, here)integer value(int n, here),这是一个数组的大小,包含字符串中的值以逗号分隔。您可以使用其他特殊字符从包含该字符的字符串中提取值。此函数将返回大小为 n 的整数数组。

    要使用

    String inp1="444,55";
    int values[]=stringToInt(inp1,2);
    

    【讨论】:

      【解决方案3】:

      来自 jse1.4String - 两个 split 方法是新的。根据 String 现在实现的 CharSequence 接口的要求,添加了 subSequence 方法。添加了三个额外的方法:matchesreplaceAllreplaceFirst

      使用 Java String.split(String regex, int limit)Pattern.quote(String s)

      例如,字符串“boo:and:foo”使用这些参数会产生以下结果:

        Regex     Limit          Result
          :         2       { "boo", "and:foo" }
          :         5       { "boo", "and", "foo" }
          :        -2       { "boo", "and", "foo" }
          o         5       { "b", "", ":and:f", "", "" }
          o        -2       { "b", "", ":and:f", "", "" }
          o         0       { "b", "", ":and:f" }
      
      String str = "abc?def,ghi?jkl,mno,pqr?stu,vwx?yz";
      String quotedText = Pattern.quote( "?" );
      // ? - \\? we have to escape sequence of some characters, to avoid use Pattern.quote( "?" );
      String[] split = str.split(quotedText, 2); // ["abc", "def,ghi?jkl,mno,pqr?stu,vwx?yz"]
      for (String string : split) {
          System.out.println( string );
      }
      

      我在 URL 参数中遇到了同样的问题,要解决它,我需要根据第一个 ? 进行拆分,以便剩余字符串包含参数值,并且需要根据 &amp; 拆分它们。

      String paramUrl = "https://www.google.co.in/search?q=encode+url&oq=encode+url";
      
      String subURL = URLEncoder.encode( paramUrl, "UTF-8");
      String myMainUrl = "http://example.com/index.html?url=" + subURL +"&name=chrome&version=56";
      
      System.out.println("Main URL : "+ myMainUrl );
      
      String decodeMainURL = URLDecoder.decode(myMainUrl, "UTF-8");
      System.out.println("Main URL : "+ decodeMainURL );
      
      String[] split = decodeMainURL.split(Pattern.quote( "?" ), 2);
      
      String[] Parameters = split[1].split("&");
      for (String param : Parameters) {
          System.out.println( param );
      }
      

      Run Javascript on the JVM with Rhino/Nashorn « 使用 JavaScript 的 String.prototype.split 函数:

      var str = "abc?def,ghi?jkl,mno,pqr?stu,vwx?yz";
      var parts = str.split(',');
      console.log( parts ); // (5) ["abc?def", "ghi?jkl", "mno", "pqr?stu", "vwx?yz"]
      console.log( str.split('?') ); // (5) ["abc", "def,ghi", "jkl,mno,pqr", "stu,vwx", "yz"]
      
      var twoparts = str.split(/,(.+)/);
      console.log( parts ); // (3) ["abc?def", "ghi?jkl,mno,pqr?stu,vwx?yz", ""]
      console.log( str.split(/\?(.+)/) ); // (3) ["abc", "def,ghi?jkl,mno,pqr?stu,vwx?yz", ""]
      

      【讨论】:

        【解决方案4】:

        :在这种情况下,您可以使用replaceAll 和一些正则表达式来获取此输入,以便您可以使用:

         System.out.println("test another :::"+test.replaceAll("(\\.*?),.*", "$1"));
        

        如果键只是一个字符串,你可以使用(\\D?),.*

        System.out.println("test ::::"+test.replaceAll("(\\D?),.*", "$1"));
        

        【讨论】:

          【解决方案5】:

          以下是您要搜索的内容:

          public String[] split(",", 2)
          

          这将给出 2 个字符串数组。斯普利特有two versions.你可以尝试的是

          String str = "abc,def,ghi,jkl";
          String [] twoStringArray= str.split(",", 2); //the main line
          System.out.println("String befor comma = "+twoStringArray[0]);//abc
          System.out.println("String after comma = "+twoStringArray[1]);//def,ghi,jkl
          

          【讨论】:

            【解决方案6】:
            String splitted[] =s.split(",",2); // will be matched 1 times. 
            
            splitted[0]  //before the first comma. `abc`
            splitted[1]  //the whole String after the first comma. `cde,def,fgh`
            

            如果您只想将cde 作为第一个逗号后的字符串。 然后你可以使用

            String splitted[] =s.split(",",3); // will be matched  2 times
            

            或者没有限制

            String splitted[] =s.split(",");
            

            不要忘记检查length 以避免ArrayIndexOutOfBound

            【讨论】:

            • splitted[1] 不会返回第一个逗号后的完整字符串
            • OP 说:2) string after first comma 这是什么意思?如果有像 `abc,cde,def,fgh` 这样的输入,那么我看到 splitted[1] 将返回 cde 不是吗? @Arjit
            • 不,@saif 你错了。 splitted[1] 将有 cde 并且 Op 想要有 cde,def,fgh 也希望你读到这个问题 我想将字符串内容分成两部分零件
            • String类型的split(String)方法不适用于参数(char)
            • 可能是错字。对于char,String 没有任何split() 方法的重载版本。使用 s.split(",") 代替。
            【解决方案7】:

            将拆分与正则表达式一起使用:

            String splitted[] = addressText.split(",",2);
            System.out.println(splitted[0]);
            System.out.println(splitted[1]);
            

            【讨论】:

              【解决方案8】:
              // Note the use of limit to prevent it from splitting into more than 2 parts
              String [] parts = s.split(",", 2);
              
              // ...setText(parts[0]);
              // ...setText(parts[1]);
              

              有关详细信息,请参阅此documentation

              【讨论】:

                【解决方案9】:
                 String s =" abc,cde,def,fgh";
                 System.out.println("subString1="+ s.substring(0, s.indexOf(",")));
                 System.out.println("subString2="+ s.substring(s.indexOf(",") + 1, s.length()));
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2021-11-16
                  • 1970-01-01
                  • 2011-11-25
                  • 2017-06-02
                  • 1970-01-01
                  • 2014-10-15
                  相关资源
                  最近更新 更多