>  기사  >  Java  >  Java의 String 클래스 예제 튜토리얼 공유

Java의 String 클래스 예제 튜토리얼 공유

零下一度
零下一度원래의
2017-05-22 10:59:471523검색

String: 문자열 유형, 여기서는 Java의 String 클래스에 대한 예제 튜토리얼을 공유하겠습니다

1. 생성자
String(byte[ ] bytes): By 바이트 배열 생성자 문자열 개체입니다.
String(char[ ] value): char 배열을 통해 문자열 객체를 구성합니다.
문자열(Sting 원본): 원본의 복사본을 구성합니다. 즉, 원본을 복사합니다.
String(StringBuffer 버퍼): StringBuffer 배열을 통해 문자열 객체를 구성합니다.
예:

 byte[] b = {'a','b','c','d','e','f','g','h','i','j'};
      char[] c = {'0','1','2','3','4','5','6','7','8','9'};
      String sb = new String(b);                 //abcdefghij
      String sb_sub = new String(b,3,2);     //de
      String sc = new String(c);                  //0123456789
      String sc_sub = new String(c,3,2);    //34
      String sb_copy = new String(sb);       //abcdefghij  
      System.out.println("sb:"+sb);
      System.out.println("sb_sub:"+sb_sub);
      System.out.println("sc:"+sc);
      System.out.println("sc_sub:"+sc_sub);
      System.out.println("sb_copy:"+sb_copy);

출력 결과: sb:abcdefghij
sb_sub:de
sc:0123456789
sc_sub:34
sb_copy:abcdefghij

2. 메소드:

설명: ① 모든 메소드는 공개됩니다.
②. 작성 형식: [수정자] ba201cadbb632e36d006c0ff71f12bffc9e3913ecc4544fea4fd34fd5904b78c

예: static int parseInt(String s)
는 다음을 나타냅니다. 메소드(parseInt)는 클래스 메소드(정적)이고, 반환 유형은 (int)이며, 메소드에는 String 유형이 필요합니다.

1. char charAt(int index): 문자열에서 문자를 가져옵니다. 여기서 매개변수 인덱스는 문자열의 서수를 나타냅니다. 문자열의 서수는 0부터 시작하여 length()-1까지 이어집니다.
예:

String s = new String("abcdefghijklmnopqrstuvwxyz");
          System.out.println("s.charAt(5): " + s.charAt(5) );

결과는 다음과 같습니다. s.charAt(5): f
2. int CompareTo(String anotherString): 현재 String 객체를 anotherString과 비교합니다. 동일 관계는 0을 반환하고, 동일하지 않으면 비교는 두 문자열의 0번째 문자부터 시작하여 동일하지 않은 첫 번째 문자 차이를 반환합니다. 또 다른 경우에는 긴 문자열의 앞부분이 더 짧은 문자열이 됩니다. 길이 차이를 반환합니다.
3.int CompareTo(Object o): o가 String 객체이면 2와 동일한 기능을 가지며, 그렇지 않으면 ClassCastException이 발생합니다.
예:

String s1 = new String("abcdefghijklmn");
            String s2 = new String("abcdefghij");
           String s3 = new String("abcdefghijalmn");
           System.out.println("s1.compareTo(s2): " + s1.compareTo(s2) ); //返回长度差
           System.out.println("s1.compareTo(s3): " + s1.compareTo(s3) ); //返回'k'-'a'的差

결과는 다음과 같습니다. s1.compareTo(s2): 4
s1.compareTo(s3): 10
4. String 객체 str과 연결됩니다.
5. 부울 contentEquals(StringBuffer sb): String 객체를 StringBuffer 객체 sb와 비교합니다.
6. static String copyValueOf(char[] data):
7. static String copyValueOf(char[] data, int offset, int count): 이 두 메서드는 char 배열을 String으로 변환합니다. 생성자는 비슷합니다.
8. boolean endWith(String suffix): 문자열 객체가 접미사로 끝나는지 여부.
예:

String s1 = new String("abcdefghij");
           String s2 = new String("ghij");
           System.out.println("s1.endsWith(s2): " + s1.endsWith(s2) );

결과는 다음과 같습니다. s1.endsWith(s2): true
9. boolean equals(Object anObject): anObject가 비어 있지 않고 현재 문자열과 동일한 경우 객체이면 true를 반환하고, 그렇지 않으면 false를 반환합니다.
10.byte[] getBytes(): String 객체를 바이트 배열로 변환합니다.
11. void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): 이 메서드는 문자열을 문자 배열에 복사합니다. 그 중 srcBegin은 복사의 시작 위치, srcEnd는 복사의 끝 위치, 문자열 값 dst는 대상 문자 배열, dstBegin은 대상 문자 배열의 복사 시작 위치이다.
예:

char[] s1 = {'I',' ','l','o','v','e',' ','h','e','r','!'};//s1=I love her!
           String s2 = new String("you!"); s2.getChars(0,3,s1,7); //s1=I love you!
           System.out.println( s1 );

결과는 다음과 같습니다. I love you!
12. int hashCode(): 현재 문자의 해시 코드를 반환합니다.
13. int indexOf(int ch): 처음으로 일치하는 문자 위치만 찾습니다.
14. int indexOf(int ch, int fromIndex): fromIndex에서 시작하여 첫 번째로 일치하는 문자 위치를 찾습니다.
15. int indexOf(String str): 첫 번째로 일치하는 문자열 위치만 찾습니다.
16. int indexOf(String str, int fromIndex): fromIndex부터 시작하여 일치하는 첫 번째 문자열 위치를 찾습니다.
예:

String s = new String("write once, run anywhere!");
              String ss = new String("run");
              System.out.println("s.indexOf('r'): " + s.indexOf('r') );
              System.out.println("s.indexOf('r',2): " + s.indexOf('r',2) );
              System.out.println("s.indexOf(ss): " + s.indexOf(ss) );

              结果为:s.indexOf('r'): 1
                      s.indexOf('r',2): 12
                      s.indexOf(ss): 12
17. int lastIndexOf(int ch)
18. int lastIndexOf(int ch, int fromIndex)
19. int lastIndexOf(String str)
20. int lastIndexOf(String str, int fromIndex) 以上四个方法与13、14、15、16类似,不同的是:找最后一个匹配的内容。

public class CompareToDemo {
      public static void main (String[] args) {
           String s1 = new String("acbdebfg");
      
           System.out.println(s1.lastIndexOf((int)'b',7));
     }
}

运行结果:5
       (其中fromIndex的参数为 7,是从字符串acbdebfg的最后一个字符g开始往前数的位数。既是从字符c开始匹配,寻找最后一个匹配b的位置。所以结果为 5)


21. int length() :返回当前字符串长度。
22. String replace(char oldChar, char newChar) :将字符号串中第一个oldChar替换成newChar。
23. boolean startsWith(String prefix) :该String对象是否以prefix开始。
24. boolean startsWith(String prefix, int toffset) :该String对象从toffset位置算起,是否以prefix开始。
     例如:

String s = new String("write once, run anywhere!");
             String ss = new String("write");
             String sss = new String("once");
             System.out.println("s.startsWith(ss): " + s.startsWith(ss) );
             System.out.println("s.startsWith(sss,6): " + s.startsWith(sss,6) );

             结果为:s.startsWith(ss): true
                     s.startsWith(sss,6): true
25. String substring(int beginIndex) :取从beginIndex位置开始到结束的子字符串。
26.String substring(int beginIndex, int endIndex) :取从beginIndex位置开始到endIndex位置的子字符串。
27. char[ ] toCharArray() :将该String对象转换成char数组。
28. String toLowerCase() :将字符串转换成小写。
29. String toUpperCase() :将字符串转换成大写。
     例如:

String s = new String("java.lang.Class String");
             System.out.println("s.toUpperCase(): " + s.toUpperCase() );
             System.out.println("s.toLowerCase(): " + s.toLowerCase() );

             结果为:s.toUpperCase(): JAVA.LANG.CLASS STRING
                  s.toLowerCase(): java.lang.class string
30. static String valueOf(boolean b)
31. static String valueOf(char c)
32. static String valueOf(char[] data)
33. static String valueOf(char[] data, int offset, int count)
34. static String valueOf(double d)
35. static String valueOf(float f)
36. static String valueOf(int i)
37. static String valueOf(long l)
38. static String valueOf(Object obj)
     以上方法用于将各种不同类型转换成Java字符型。这些都是类方法。

Java中String类的常用方法:

public char charAt(int index)
返回字符串中第index个字符;
public int length()
返回字符串的长度;
public int indexOf(String str)
返回字符串中第一次出现str的位置;
public int indexOf(String str,int fromIndex)
返回字符串从fromIndex开始第一次出现str的位置;
public boolean equalsIgnoreCase(String another)
比较字符串与another是否一样(忽略大小写);
public String replace(char oldchar,char newChar)
在字符串中用newChar字符替换oldChar字符
public boolean startsWith(String prefix)
判断字符串是否以prefix字符串开头;
public boolean endsWith(String suffix)
判断一个字符串是否以suffix字符串结尾;
public String toUpperCase()
返回一个字符串为该字符串的大写形式;
public String toLowerCase()
返回一个字符串为该字符串的小写形式
public String substring(int beginIndex)
返回该字符串从beginIndex开始到结尾的子字符串;
public String substring(int beginIndex,int endIndex)
返回该字符串从beginIndex开始到endsIndex结尾的子字符串
public String trim()
返回该字符串去掉开头和结尾空格后的字符串
public String[] split(String regex)
将一个字符串按照指定的分隔符分隔,返回分隔后的字符串数组

实例:  

public class SplitDemo{
     public static void main (String[] args) {
             String date = "2008/09/10";
            String[ ] dateAfterSplit= new String[3];
            dateAfterSplit=date.split("/");         //以“/”作为分隔符来分割date字符串,并把结果放入3个字符串中。
            for(int i=0;i<dateAfterSplit.length;i++)
                       System.out.print(dateAfterSplit[i]+" ");
      }
}

运行结果:2008 09 10          //结果为分割后的3个字符串

实例:

TestString1.java:程序代码public class TestString1{    public static void main(String args[]) {        String s1 = "Hello World" ;        String s2 = "hello world" ;        System.out.println(s1.charAt(1)) ;        System.out.println(s2.length()) ;        System.out.println(s1.indexOf("World")) ;        System.out.println(s2.indexOf("World")) ;        System.out.println(s1.equals(s2)) ;        System.out.println(s1.equalsIgnoreCase(s2)) ;
        String s = "我是J2EE程序员" ;        String sr = s.replace(&#39;我&#39;,&#39;你&#39;) ;        System.out.println(sr) ;    }}
TestString2.java:

程序代码

public class TestString2
{
    public static void main(String args[]) {
        String s = "Welcome to Java World!" ;
        String s2 = "   magci   " ;
        System.out.println(s.startsWith("Welcome")) ;
        System.out.println(s.endsWith("World")) ;
        String sL = s.toLowerCase() ;
        String sU = s.toUpperCase() ;
        System.out.println(sL) ;
        System.out.println(sU) ;
        String subS = s.substring(11) ;
        System.out.println(subS) ;
        String s1NoSp = s2.trim() ;
        System.out.println(s1NoSp) ;
    }

【相关推荐】

1. java中String是对象还是类?详解java中的String

2. 总结Java 中String类的实例教程

3. Java中String类的常用方法是什么?总结Java中String类的常用方法

4. 分享java String部分源码解读

위 내용은 Java의 String 클래스 예제 튜토리얼 공유의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.