字符串常用API
import java.util.Locale;
public class OftenAPI {
public static void main(String[] args) {
// 1、public int length(): 获取字符串的长度
String s1 = "askjbkajsdb";
System.out.println(s1.length());
// 2、public char charAt(int index): 获取某个索引位置处的字符
System.out.println(s1.charAt(4));
// 3、public char[] toCharArray(): 把字符串转换成字符数组
char[] str1 = s1.toCharArray();
System.out.println(str1);
// 4、public String substring(int beginIndex, int endIndex) :截取内容,(包前不包后的)
System.out.println(s1.substring(1, 4));
// 5、public String substring(int beginIndex):从当前索引一直截取到末尾
System.out.println(s1.substring(4));
// 6、public String replace(CharSequence target, CharSequence replacement):使用新值,将字符串中的旧值替换,得到新的字符串
String s2 = s1.replace("a", "z");
System.out.println(s2);
// 7、public boolean contains(CharSequence s):判断字符串中是否包含了某个字符串
System.out.println(s2.contains("a"));
// 8、public boolean startsWith(String prefix):判断字符串是否以某个字符串内容开头
System.out.println(s1.startsWith("a"));
// 9、public String[] split(String s): 按照某个内容把字符串分割成字符串数组返回
String a = "a,v,c,e,f,b,r";
String[] b = a.split(",");
for (int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}
// 10、public String trim():删除字符串首尾空格,返回一个新字符串
String a1 = " ergbergb ";
System.out.println(a1.trim());
// 11、public String toUpperCase():将此 String所有字符转换为大写
System.out.println(a1.trim().toUpperCase());
}
}
运行结果:
11
b
askjbkajsdb
skj
bkajsdb
zskjbkzjsdb
false
true
a
v
c
e
f
b
r
ergbergb
ERGBERGB
Process finished with exit code 0
打印随机位数验证码—用字符串
import java.util.Random;
public class String_Test {
public static void main(String[] args) {
System.out.println(getString(5));
}
public static String getString(int num) {
String s = "";
String str = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
Random r = new Random();
for (int i = 0; i < num; i++) {
int index = r.nextInt(str.length());//取0到str长度的随机数,赋值给index
s += str.charAt(index);//查询字符串中index位置的字符
}
return s;
}
}