String中常见API(一)
1.查找字符串的长度
package com.tedu.String;
public class StrLengthDemo {
public static void main(String[] args) {
String str = "a你b c";
System.out.println(str.length());
}
}
2.查找给定字符在字符串中位置
package com.tedu.String;
public class IndexDemo {
public static void main(String[] args) {
String str = "this is java!";
int index1 = str.indexOf("a");
System.out.println(index1);
int index2 = str.indexOf("is");
System.out.println(index2);
index2 = str.indexOf("is",4);
System.out.println(index2);
index2 = str.lastIndexOf("is");
System.out.println(index2);
}
}
3.截取字符串
package com.tedu.String;
public class SubStringDemo {
public static void main(String[] args) {
String str = "abcdefghijklmn";
String s = str.substring(6,9);
System.out.println(s);
s = str.substring(6);
System.out.println(s);
}
}
API调用使用练习
package com.tedu.String;
public class StringTest {
public static void main(String[] args) {
String s1 = "www.baidu.com";
String s2 = "http://www.tedu.cn";
String s3 = "http://doc.tarena.com.cn";
s1 = getHostName(s1);
s2 = getHostName(s2);
s3 = getHostName(s3);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
public static String getHostName(String url) {
int start = url.indexOf(".") + 1;
int end = url.indexOf(".", start);
return url.substring(start, end);
}
}