当前位置:主页 > 软件编程 > .NET代码 >

string类的使用方法详解

时间:2020-12-07 17:16:09 | 栏目:.NET代码 | 点击:

String:字符串类型

1、构造函数。

	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);
String sb_sub = new String(b,3,2);
String sc = new String(c);
String sc_sub = new String(c,3,2);
String sb_copy = new String(sb);

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、方法。
说明:
1. 所有方法均为public;
2. 书写格式:[修饰符] <返回类型> <方法名([参数列表])>

如:
static int parseInt(String s) 表示:此方法(parseInt)为类方法(static),返回类型为(int),方法所需参数为String类型。



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


	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


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


	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!


	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


	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


	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

您可能感兴趣的文章:

相关文章