【问题标题】:Android How to get first character of string? [closed]Android 如何获取字符串的第一个字符? [关闭]
【发布时间】:2018-06-22 20:03:42
【问题描述】:

如何获取字符串的第一个字符?

string test = "StackOverflow";

第一个字符 = "S"

【问题讨论】:

标签: java string


【解决方案1】:
String test = "StackOverflow"; 
char first = test.charAt(0);

【讨论】:

  • substring(0,1) 如果您希望它作为字符串而不是字符
  • 感谢朋友,完美
  • 如果你这样做textView.setText(test.charAt(0)) 会抛出一个错误,因为它是一个字符而不是字符串。
  • 这就是@Thilo 想说的:` **String test = "StackOverflow";字符串优先 = test.substring(0,1);**`
【解决方案2】:

另一种方法是

String test = "StackOverflow";
String s=test.substring(0,1);

在这你得到String的结果

【讨论】:

    【解决方案3】:

    你可以参考这个link,第4点。

    public class StrDemo
    {
    public static void main (String args[])
    {
        String abc = "abc";
    
        System.out.println ("Char at offset 0 : " + abc.charAt(0) );
        System.out.println ("Char at offset 1 : " + abc.charAt(1) );
        System.out.println ("Char at offset 2 : " + abc.charAt(2) );
    
      //Also substring method
       System.out.println(abc.substring(1, 2));
       //it will print 
    

    bc

    // as starting index to end index here in this case abc is the string 
       //at 0 index-a, 1-index-b, 2- index-c
    
    // This line should throw a StringIndexOutOfBoundsException
        System.out.println ("Char at offset 3 : " + abc.charAt(3) );
     }
    }
    

    【讨论】:

      【解决方案4】:

      使用 charAt():

      public class Test {
         public static void main(String args[]) {
            String s = "Stackoverflow";
            char result = s.charAt(0);
            System.out.println(result);
         }
      }
      

      这是tutorial

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-26
        • 2021-04-15
        • 2015-07-02
        • 1970-01-01
        • 1970-01-01
        • 2018-06-04
        相关资源
        最近更新 更多