02字符串

125 阅读2分钟

02字符串

介绍:字符串时使用双引号括起来的字符序列。
相关操作:
1.字符串的创建
//1.1创建一个字符串"hello":
String str = "hello";
//或者
String str = new String("hello");

//1.2使用字符数组创建字符串:
char[] a = {'h','e','l','l','o'};
String str = new String(a);

//1.3创建可修改的字符串:
StringBuffer str = new StringBuffer();
//创建一个可修改且大小为2的字符串:
StringBuffer str = new StringBuffer(2);
//创建一个可修改且初始值为hello的字符串:
StringBuffer str = new StringBuffer("hello");
2.常用方法
//String str = "hello";
//StringBuffer strbuffer = new StringBuffer("hello");

//2.1字符串的拼接:字符串1.concat(字符串2)
String str = "hello" + "world";
//或者
String str1 = "hello";
String str2 = "world";
String str = str1.concat(str2);
输出结果:str = helloworld

//2.2获取字符串长度:字符串.length()
int len = str.length();
输出结果:5;

//2.3字符串的判等:字符串1.equals(字符串2) / 字符串1.equalsIgnoreCase(字符串2)
String str1 = "world";
boolean flag = str.equals(str1);
输出结果:flag = false;
//忽略大小写的判等:
String str1 = "Hello";
boolean flag = str.equalsIgnoreCase(str1);
输出结果:flag = true;

//2.4字符串的比较:字符串1.compareTo(字符串2)
String str = "a";
String str1 = "b";
int x = str.compareTo(str1);
输出结果:x = -1;    //如果前者大于后者为1,等于为0,小于为-1

//2.5字符串的截取:字符串1.substring(起始位置,结束位置)
String str1 = str.substring(1,4);
输出结果:str1 = "ell";

//2.6查找字符串子串:字符串1.indexOf(子串,起始查找位置) / 字符串1.charAt(字符)
String str = "hello";
int index = str.indexOf("l",3);
输出结果:index = 3;
//根据索引查找字符串:
char i = str.charAt(0);
输出结果:i = 'h';

//2.7字符串的替换:字符串.replace(旧字符,新字符)
String oldstr = "llo";
String newstr = " ";
str = str.replace(oldstr,newstr);
输出结果:str = "he";

//2.8去除字符串中首尾空格:字符串.trim()
String newstr = " hello ";
newstr = newstr.trim();
输出结果:newstr = "hello";

//2.9字符串转换大小写:字符串.toUpperCase() / 字符串.toLowerCase()
String str = "Hello";
String upstr = str.toUpperCase();
String lowstr = str.toLowerCase();
输出结果:upstr = "HELLO"  lowstr = "hello"

//2.10字符串的分割:字符串.split(字符)
String str = "a,b,c,d,e";
String[] a = str.split(",");
输出结果:a = ["a","b","c","d","e"];

//2.11将字符串转化为字符数组:字符串.toCharArray()
char[] arr = str.toCharArray();
输出结果:arr = ['h','e','l','l','o'];

//2.12将字符串反转:字符串.reverse()
strbuffer.reverse();
输出结果:strbuffer = "olleh";

//2.13删除字符串指定位置的字符:字符串.deleteCharAt(索引)
strbuffer.deleteCharAt(2);
输出结果:strbuffer = "helo";

//2.14在字符串指定位置之后插入字符串:字符串.insert(索引,字符串)
strbuffer.insert(0,"hello");
输出结果:strbuffer = "hellohello";

//2.15删除字符串指定区间的子序列:字符串.delete(起始位置,结束位置)
strbuffer.delete(0,1);
输出结果:strbuffer = "ello";

//2.16将字符串追加到另一字符串之后:字符串1.append(字符串2)
String s = "ok";
strbuffer.append(s);
输出结果:strbuffer = "hellook";