【问题标题】:Get string character by index按索引获取字符串字符
【发布时间】:2012-06-29 02:35:36
【问题描述】:

我知道如何计算出字符串中某个字符或数字的索引,但是有什么预定义的方法可以让我在 nth 位置给我这个字符吗?所以在字符串“foo”中,如果我询问索引为 0 的字符,它将返回“f”。

注意 - 在上述问题中,“字符”不是指 char 数据类型,而是字符串中的字母或数字。这里重要的是,当调用该方法时我没有收到一个字符,而是一个字符串(长度为 1)。而且我知道 substring() 方法,但我想知道是否有更简洁的方法。

【问题讨论】:

  • 是吗?答案很简单。
  • 您是否注意到他不想要char 值?而且他知道如何做substring(),但只是想要一种“更整洁”的方式。仅供参考,我可以说substring() 是最简洁的方式。
  • @user845279 Character.toString 满足所有必要的要求,而且一点也不乱。
  • @pythonscript 我同意,但这与直接使用substring() 并没有太大区别。
  • 我参加这个聚会迟到了,但@RicardoAltamirano 有点误会了。 String.substring(int, int)endIndex(第二个参数)是一个独占索引,它不会index + 1抛出异常,只要index < length() - - 即使对于字符串中的最后一个字符也是如此。

标签: java string


【解决方案1】:

CharAt 函数不工作

Edittext.setText(YourString.toCharArray(),0,1);

这段代码运行良好

【讨论】:

    【解决方案2】:

    CodePointAt 代替 charAt 使用起来更安全。当 strtng 中有表情符号时,charAt 可能会中断。

    【讨论】:

      【解决方案3】:

      如果有人在使用 kotlin,代码是:

      var oldStr: String = "kotlin"
      var firstChar: String = oldStr.elementAt(0).toString()
      Log.d("firstChar", firstChar.toString())
      

      这将返回位置 1 的字符,在本例中为 k 请记住,索引从位置 0 开始,因此在此示例中: kotlin 将是 k=position 0, o=position 1, t=position 2, l=position 3, i=position 4 and n=position 5

      【讨论】:

        【解决方案4】:

        您要查找的方法是charAt。这是一个例子:

        String text = "foo";
        char charAtZero = text.charAt(0);
        System.out.println(charAtZero); // Prints f
        

        有关详细信息,请参阅Java documentation on String.charAt。如果你想要另一个简单的教程,this onethis one

        如果您不希望将结果作为 char 数据类型,而是作为字符串,则可以使用 Character.toString 方法:

        String text = "foo";
        String letter = Character.toString(text.charAt(0));
        System.out.println(letter); // Prints f
        

        如果您想了解有关 Character 类和 toString 方法的更多信息,我从 the documentation on Character.toString 中提取了我的信息。

        【讨论】:

        • “这里重要的是,当调用该方法时我没有收到一个字符,而是一个字符串”,但无论如何感谢(upvote):D
        • 我认为 Sylvain Leroux 的回答更好。doc about Character
        • 我同意@ChaojunZhong this 是一个更合适的答案,因为不建议使用 charAt() 因为当你有需要 2 个代码单元的字符时你会遇到问题。
        【解决方案5】:

        这是正确的代码。如果您使用的是 zybooks,这将解决所有问题。

        for (int i = 0; i<passCode.length(); i++)
        {
            char letter = passCode.charAt(i);
            if (letter == ' ' )
            {
                System.out.println("Space at " + i);
            }
        }
        

        【讨论】:

          【解决方案6】:

          建议的答案均不适用于用于编码Unicode Basic Multiligual Plane 之外的字符的代理对。

          这是一个使用三种不同技术迭代字符串“字符”的示例(包括使用 Java 8 流 API)。请注意,此示例包括 Unicode 补充多语言平面 (SMP) 的字符。您需要合适的字体才能正确显示此示例和结果。

          // String containing characters of the Unicode 
          // Supplementary Multilingual Plane (SMP)
          // In that particular case, hieroglyphs.
          String str = "The quick brown ? jumps over the lazy ????";
          

          字符迭代

          第一个解决方案是对字符串的所有char进行简单循环:

          /* 1 */
          System.out.println(
                  "\n\nUsing char iterator (do not work for surrogate pairs !)");
          for (int pos = 0; pos < str.length(); ++pos) {
              char c = str.charAt(pos);
              System.out.printf("%s ", Character.toString(c));
              //                       ^^^^^^^^^^^^^^^^^^^^^
              //                   Convert to String as per OP request
          }
          

          代码点迭代

          第二种解决方案也使用显式循环,但访问单个 带有codePointAt 的代码点并将循环索引相应地增加到charCount

          /* 2 */
          System.out.println(
                  "\n\nUsing Java 1.5 codePointAt(works as expected)");
          for (int pos = 0; pos < str.length();) {
              int cp = str.codePointAt(pos);
          
              char    chars[] = Character.toChars(cp);
              //                ^^^^^^^^^^^^^^^^^^^^^
              //               Convert to a `char[]`
              //               as code points outside the Unicode BMP
              //               will map to more than one Java `char`
              System.out.printf("%s ", new String(chars));
              //                       ^^^^^^^^^^^^^^^^^
              //               Convert to String as per OP request
          
              pos += Character.charCount(cp);
              //     ^^^^^^^^^^^^^^^^^^^^^^^
              //    Increment pos by 1 of more depending
              //    the number of Java `char` required to
              //    encode that particular codepoint.
          }
          

          使用 Stream API 迭代代码点

          第三种解决方案与第二种基本相同,但使用Java 8 Stream API

          /* 3 */
          System.out.println(
                  "\n\nUsing Java 8 stream (works as expected)");
          str.codePoints().forEach(
              cp -> {
                  char    chars[] = Character.toChars(cp);
                  //                ^^^^^^^^^^^^^^^^^^^^^
                  //               Convert to a `char[]`
                  //               as code points outside the Unicode BMP
                  //               will map to more than one Java `char`
                  System.out.printf("%s ", new String(chars));
                  //                       ^^^^^^^^^^^^^^^^^
                  //               Convert to String as per OP request
              });
          

          结果

          当您运行该测试程序时,您会获得:

          Using char iterator (do not work for surrogate pairs !)
          T h e   q u i c k   b r o w n   ? ?   j u m p s   o v e r   t h e   l a z y   ? ? ? ? ? ? ? ? 
          
          Using Java 1.5 codePointAt(works as expected)
          T h e   q u i c k   b r o w n   ?   j u m p s   o v e r   t h e   l a z y   ? ? ? ? 
          
          Using Java 8 stream (works as expected)
          T h e   q u i c k   b r o w n   ?   j u m p s   o v e r   t h e   l a z y   ? ? ? ? 
          

          如您所见(如果您能够正确显示象形文字),第一个解决方案无法正确处理 Unicode BMP 之外的字符。另一方面,其他两个解决方案可以很好地处理代理对。

          【讨论】:

            【解决方案7】:

            就这么简单:

            String charIs = string.charAt(index) + "";
            

            【讨论】:

              【解决方案8】:

              您可以使用String.charAt(int index) 方法结果作为String.valueOf(char c) 的参数。

              String.valueOf(myString.charAt(3)) // This will return a string of the character on the 3rd position.
              

              【讨论】:

                【解决方案9】:

                像这样:

                String a ="hh1hhhhhhhh";
                char s = a.charAt(3);
                

                【讨论】:

                • OP 声明需要长度为 1 的 String不是 char
                • 其他 6 个答案(包括已接受的答案)建议 charAt() 作为可能的解决方案。这个答案增加了什么?
                • 另外,您似乎在暗示 charAt() 使用基于 1 的索引,因为 a 中的唯一不同字符位于第三位。如果这是真的,那么你最好说或解释这一点,而不是暗示它。实际上,这不是正确的:charAt() 使用基于 0 的索引,因此 s 将是 'h'
                【解决方案10】:

                你想要.charAt()

                Here's a tutorial

                "mystring".charAt(2)
                

                返回s

                如果你一心想拥有一个字符串,有几种方法可以将 char 转换为字符串:

                String mychar = Character.toString("mystring".charAt(2));
                

                或者

                String mychar = ""+"mystring".charAt(2);
                

                甚至

                String mychar = String.valueOf("mystring".charAt(2));
                

                例如。

                【讨论】:

                • @ametren 字符串连接是否优于Character.toString
                • 我认为这可能归结为个人喜好问题。你也可以String mychar = String.valueOf("mystring".charAt(2));
                • 继续说,在这种情况下,我个人的偏好是String mychar = ""+"mystring".charAt(2);,因为它是最简洁的。其他人对此会有不同的看法。
                【解决方案11】:

                charAt 与您不获取字符的要求相结合的混合方法可能是

                newstring = String.valueOf("foo".charAt(0));
                

                但老实说,这并不比 substring() 真正“整洁”。

                【讨论】:

                  【解决方案12】:

                  考虑到您的要求,您对substring() 非常满意。标准方式是charAt(),但您说您不会接受 char 数据类型。

                  【讨论】:

                  • 很公平。但是,由于 char 是一种原始类型,我假设 toString() 无法处理它,而 valueOf() 仅适用于数字(我想,我可能错了),那么如何将 char 转换为字符串呢?
                  • "在上面的问题中,"字符"我不是指 char 数据类型"——我不认为这是"我不会接受char"跨度>
                  • @Bluefire 查看我的回答。 Character.toString 应该可以工作(它是来自 Character 类的静态方法。
                  猜你喜欢
                  • 2021-07-19
                  • 1970-01-01
                  • 2019-07-22
                  • 1970-01-01
                  • 2014-07-02
                  • 2011-11-21
                  • 2017-12-06
                  • 1970-01-01
                  • 2014-12-02
                  相关资源
                  最近更新 更多