一、String(概述)
- /*
- String概述:
- */
- class StringDemo
- {
- public static void main(String[] args)
- {
- String s1="abc";/*s1是一个类类型变量,"abc"是一个对象。
- 字符串最大特点:一旦被初始化就不可改变。
- "abc"存在常量池中。
- */
- String s2=new String("abc");
- /*
- s1和s2的区别:
- s1在内存中有一个对象。
- s2在内存中有两个对象。
- */
- System.out.println(s1==s2);
- System.out.println(s1.equals(s2));/*String类复写了Object类的equals方法。
- 该方法用于判断字符串是否相同。
- */
- }
- }
二、String(常见功能-获取和判断)
String类适用于描述字符串事物,那么它就提供了多个方法对字符串进行操作。
常见的操作有哪些?
"abcd"
1.获取:
1.1字符串中包含的字符数,也就是字符串的长度。
int length():获取长度。
1.2根据位置获取某个位置的字符。
char charAt(int index):
1.3根据字符获取该字符在字符串中的位置。
int indexOf(int ch) :返回的是ch在字符串中第一次出现的位置。
int indexOf(int ch,int fromIndex) :从fromIndex指定位置开始,获取ch在字符串中第一次出现的位置。
int indexOf(String str) :返回的是str在字符串中第一次出现的位置。
int lastIndexOf(int ch):反向索引一个字符出现的位置。
2.判断:
2.1字符串中是否包含某一个子串
boolean contains(CharSequence s):当且仅当此字符串包含指定的 char 值序列时,返回 true。
特殊之处:int indexOf(String str) :返回的是str在字符串中第一次出现的位置,不存在返回-1。
所以也可以用于对指定判断是否包含。例如:if(str.indexOf("aa")!=-1)
而且该方法既可以判断,又可以获取出现的位置。
2.2字符串中是否有内容
boolean isEmpty() :当且仅当 length() 为 0 时返回 true。
2.3字符串是否是以指定内容开头
boolean startsWith(String prefix) :测试此字符串是否以指定的前缀开始。
2.4字符串是否是以指定内容结尾
boolean endsWith(String suffix) :测试此字符串是否以指定的后缀结束。
2.5判断字符串的内容是否相同(复写了Object类的equals方法)
boolean equals(Object anObject):将此字符串与指定的对象比较。当且仅当该参数不为 null, 并且是与此对象表示相同字符序列的 String 对象时,结果才为 true。
2.6判断字符串的内容是否相同
boolean equalsIgnoreCase(String anotherString):将此 String 与另一个 String 比较,不考虑大小写。如果两个字符串的长度相同,并且其中的相应字符都相等(忽略大小写),则认为这 两个字符串是相等的。
3.转换:
3.1将字符数组转换成字符串
构造函数:
String(char[] value):分配一个新的 String,使其表示字符数组参数中当前包含的字符序 列。 该字符数组的内容已被复制;后续对字符数组的修改不会影响新创建的字符串。
String(char[] value,int offset,int count):分配一个新的 String,它包含取自字符数组参数一个子数组的字符。offset 参数是子数组第一个字符的索引,count 参数指定子数组的长度。该子 数组的内容已被复制;后续对字符数组的修改不会影响新创建的字符串。
静态方法:
static String copyValueOf(char[] data):返回指定数组中表示该字符序列的 String。
static String copyValueOf(char[] data,int offset,int count):返回指定数组中表示该字符序列的 String。 data - 字符数组。offset - 子数组的初始偏移量。count - 子数组的长度。
static String valueOf(char c):返回 char 参数的字符串表示形式。
3.2将字符串转换成字符数组 *
char[] toCharArray():将此字符串转换为一个新的字符数组。
3.3将字节数组转换成字符串
String(byte[] bytes):通过使用平台的默认字符集解码指定的 byte 数组,构造一个新的 String。新 String 的长度是字符集的函数,因此可能不等于 byte 数组的长度。
String(byte[] bytes,int offset,int length):通过使用平台的默认字符集解码指定的 byte 子数组,构造一个新的 String。新 String 的长度是字符集的函数,因此可能不等于该子数组的长度。
3.4将字符串转换成字节数组
byte[] getBytes():使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一 个新的 byte 数组中。
byte[] getBytes(Charset charset):使用给定的 charset 将此 String 编码到 byte 序列,并将结 果存储到新的 byte 数组。
3.5将基本数据类型转换为字符串
static String valueOf(char c):返回 char 参数的字符串表示形式。
static String valueOf(char[] data,int offset,int count):返回 char 数组参数的特定子数组的字符 串表示形式。 offset 参数是子数组的第一个字符的索引。count 参数指定子数组的长度。 字符数组的内容已被复制,后续修改不会影响新创建的字符串。
static String valueOf(double d):返回 double 参数的字符串表示形式。 该表示形式恰好是单参数的 Double.toString 方法返回的结果。
static String valueOf(int i):返回 int 参数的字符串表示形式。 该表示形式恰好是单参数的 Integer.toString 方法返回的结果。
例如:
3+""; //String.valueOf(3);
特殊:字符串和字节数组在转换过程中,是可以指定编码表的。
4.替换:
String replace(char oldChar,char newChar):返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。
String replace(CharSequence target,CharSequence replacement):使用指定的字面值替换序列替换此字符串所有匹配字面值目标序列的子字符串。该替换从字符串的开头朝末尾执行,例 如,用 "b" 替换字符串 "aaa" 中的 "aa" 将生成 "ba" 而不是 "ab"。
5.切割:
String[] split(String regex):根据给定正则表达式的匹配拆分此字符串。 该方法的作用就像是使用给定的表达式和限制参数 0 来调用两参数 split 方法。因此,所得数组中不包括结尾 空字符串。
String[] split(String regex,int limit):根据匹配给定的正则表达式来拆分此字符串。 此方法返回 的数组包含此字符串的子字符串,每个子字符串都由另一个匹配给定表达式的子字符串终 止,或者由此字符串末尾终止。数组中的子字符串按它们在此字符串中出现的顺序排列。 如果表达式不匹配输入的任何部分,那么所得数组只具有一个元素,即此字符串。
6.获取字串:
String substring(int beginIndex,int endIndex):返回一个新字符串,它是此字符串的一个子字符 串。该子字符串从指定的 beginIndex 处开始,直到索引 endIndex - 1 处的字符。因此,该 子字符串的长度为 endIndex-beginIndex。
String substring(int beginIndex):返回一个新的字符串,它是此字符串的一个子字符串。该子 字符串从指定索引处的字符开始,直到此字符串末尾。
7.转换,去除空格,比较:
7.1将字符串转换成大写或者小写
String toUpperCase():使用默认语言环境的规则将此 String 中的所有字符都转换为大写。此方法等效于 toUpperCase(Locale.getDefault())。
String toLowerCase():使用默认语言环境的规则将此 String 中的所有字符都转换为小写。这等效于调用 toLowerCase(Locale.getDefault())。
7.2将字符串两端的多个空格去除
String trim():返回字符串的副本,忽略前导空白和尾部空白。
7.3对两个字符串进行自然顺序的比较。
int compareTo(String anotherString):按字典顺序比较两个字符串。该比较基于字符串中各个字 符的 Unicode 值。按字典顺序将此 String 对象表示的字符序列与参数字符串所表示的字符 序列进行比较。如果按字典顺序此 String 对象位于参数字符串之前,则比较结果为一个负 整数。如果按字典顺序此 String 对象位于参数字符串之后,则比较结果为一个正整数。如 果这两个字符串相等,则结果为 0;compareTo 只在方法 equals(Object) 返回 true 时才返 回 0。
- /*
- 测试:
- 常见功能
- */
- class StringMethodDemo
- {
- public static void method_7()
- {
- String s=" Hello Java ";
- sop(s.toLowerCase());
- sop(s.toUpperCase());
- sop(s.trim());
- String s1="abc";
- String s2="aaa";
- sop(s1.compareTo(s2));
- }
- public static void method_sub()
- {
- String s="abcdefg";
- sop(s.substring(2));//从指定位置开始到结尾。如果角标不存在,会出现字符串角标越界异常。
- sop(s.substring(2,4));//包含头,不包含尾。获取全部:s.substring(0,s.length());
- }
- public static void method_split()
- {
- String s="zhangsan,lisi,wangwu";
- String[] arr= s.split(",");
- for(int i=0;i<arr.length;i++)
- {
- sop(arr[i]);
- }
- }
- public static void method_replace()
- {
- String s="hello java";
- String s1=s.replace('a','n');//如果要替换的字符不存在,返回的还是原字符串
- sop("s="+s);
- sop("s1="+s1);
- }
- public static void method_trans()
- {
- char[] arr={'a','b','c','d','e','f'};
- String s=new String(arr,1,3);
- sop("s="+s);
- String s1="yangcheng";
- char[] chs=s1.toCharArray();
- for(int i=0;i<chs.length;i++)
- {
- sop("ch["+i+"]="+chs[i]);
- }
- }
- public static void method_is()
- {
- String str="ArrayDemo.java";
- sop(str.startsWith("Array"));//判断文件名是否是Array单词开头。
- sop(str.endsWith(".java"));//判断文件名称是否是.java
- sop(str.contains("Demo"));//判断文件中是否包含Demo
- }
- public static void method_get()
- {
- String str="abcdefasgpireeqfrf";
- sop(str.length());//长度
- sop(str.charAt(2));/*根据索引获取字符。注意:当访问字符串中不存在的角标时,
- 会发生StringIndexOutOfBoundsException异常。
- */
- sop(str.indexOf('a'));//根据字符获取索引,如果没有找到该字符,返回-1
- sop(str.lastIndexOf("r"));//返回指定字符在此字符串中最后一次出现处的索引。
- }
- public static void main(String[] args)
- {
- String s1="abc";
- String s2=new String("abc");
- String s3="abc";//常量池中已经有"abc",不再分配内存存储"abc"
- System.out.println(s1==s2);
- System.out.println(s1==s3);
- method_get();
- method_is();
- method_trans();
- method_replace();
- method_split();
- method_sub();
- method_7();
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
三、String(字符串练习)
- /*
- 项目1:
- 模拟一个trim方法,取出字符串两端的空格。
- 思路:
- 1.判断字符串第一个位置是否是空格,如果是,继续向下判断,直到不是空格为止。
- 结尾处判断空格也是这样的。
- 2.当开始和结尾都判断不是空格时,就要是获取的字符串。
- */
- class StringTest1
- {
- public static void sop(String str)
- {
- System.out.println(str);
- }
- public static String myTrim(String str)
- {
- int start=0,end=str.length()-1;
- while(start<=end && str.charAt(start)==' ')
- start++;
- while(start<end && str.charAt(end)==' ')
- end--;
- return str.substring(start,end+1);
- }
- public static void main(String[] args)
- {
- String s=" How are you ";
- sop("s="+s);
- sop("s="+myTrim(s));
- }
- }
- /*
- 项目2:
- 将一个字符串进行反转,将字符串中指定部分进行反转。
- 思路:
- 1.曾经学习过对数组元素进行反转。
- 2.将字符串编程数组,对数组反转。
- 3.将反转后的数组变成字符串。
- 4.只要将或反转的部分的开始和结束位置最为参数传递即可。
- */
- class StringTest2
- {
- public static void sop(String str)
- {
- System.out.println(str);
- }
- public static String reverseString(String s)
- {
- return reverseString(s,0,s.length()-1);//将数组变成字符串
- }
- public static String reverseString(String s,int start,int end)
- {
- char[] chs=s.toCharArray();//字符串变数组
- reverse(chs,start,end);//反转数组
- return new String(chs);//将数组变成字符串
- }
- private static void reverse(char[] arr,int x,int y)
- {
- for(int start=x,end=y-1;start<end;start++,end--)
- {
- swap(arr,start,end);
- }
- }
- private static void swap(char[] arr,int x,int y)
- {
- char temp=arr[x];
- arr[x]=arr[y];
- arr[y]=temp;
- }
- public static void main(String[] args)
- {
- String s=" ab cd ";
- sop("s="+s);
- sop("s="+reverseString(s));
- sop("s="+reverseString(s,3,5));//包含头,不包含尾
- }
- }
- /*
- 项目3:
- 获取一个字符串在另一个字符串中出现的次数。
- "askkdfsdssddkkwerkk";
- 思路:
- 1.定义一个计数器
- 2.获取kk第一次出现的位置
- 3.从第一次出现位置后剩余的字符串中继续获取kk出现的位置。每获取一次计数一次。
- 4.当获取不到时,计数完成。
- */
- class StringTest3
- {
- public static void sop(String str)
- {
- System.out.println(str);
- }
- public static int getSubCount(String str,String key)//方法1
- {
- int count=0;
- int index=0;
- while((index=str.indexOf(key))!=-1)
- {
- str=str.substring(index+key.length());
- count++;
- }
- return count;
- }
- public static int getSubCount_2(String str,String key)//方法2
- {
- int count=0;
- int index=0;
- while((index=str.indexOf(key,index))!=-1)
- {
- index=index+key.length();
- count++;
- }
- return count;
- }
- public static void main(String[] args)
- {
- String str1="askkdfsdssddkkwer";
- String str2="kk";
- sop("s="+str1);
- sop("子串:"+str2);
- sop("count="+getSubCount(str1,"kk"));
- sop("count="+getSubCount_2(str1,"kk"));
- //sop("count="+str1.split(str2).length);//不建议使用
- }
- }
- /*
- 项目4:
- 获取两个字符串中最大相同字串。第一动作:将短的那个串进行长度依次递减的字串打印。
- "abcsfwgtrhello6frgerhq"
- "sdhellovb"
- 思路:
- 1.将短的那个字串按照长度递减的方式获取到。
- 2.将每获取到的字串去长串中判断是否包含。如果包含,就找到了。
- */
- class StringTest4
- {
- public static void sop(String str)
- {
- System.out.println(str);
- }
- public static String getMaxSubString(String s1,String s2)
- {
- String max="",min="";
- max=s1.length()>s2.length()?s1:s2;//长串
- min=(max==s1)?s2:s1;//短串
- for(int i=0;i<min.length();i++)
- {
- for(int j=0,k=min.length()-i;k!=min.length()+1;j++,k++)
- {
- String temp=min.substring(j,k);
- if(max.contains(temp))
- return temp;
- }
- }
- return "";
- }
- public static void main(String[] args)
- {
- String s1="abcsfwgtrhello6frgerhq";
- String s2="sdhellovb";
- sop("s1="+s1);
- sop("s2="+s2);
- sop(getMaxSubString(s1,s2));
- sop(getMaxSubString(s2,s1));
- }
- }
四、StringBuffer(常见功能-添加)
StringBuffer是一个字符串缓冲区,是一个容器。
特点:
1.长度可以变化。
2.可以操作多个数据类型。
3.最终会通过toString方法变成字符串。
1.存储
StringBuffer append():将指定的数据作为参数添加到已有数据的结尾处。
StringBuffer insert(intdex,数据):可以将数据插入到指定index位置。
2.删除
StringBuffer delete(start,end):删除缓冲区中的数据。包含start不包含end。
StringBuffer deleteCharAt(index):删除指定位置的字符。
3.获取
char charAt(int index):获取index位置的字符。
int indexOf(String str) :返回第一次出现的指定子字符串在该字符串中的索引。
int lastIndexOf(String str) :返回最右边出现的指定子字符串在此字符串中的索引。
int length() :返回长度(字符数)。
String substring(int start, int end) :返回一个新的 String,它包含此序列当前所包含的字符子序列。
4.修改
StringBuffer replace(start,end,string):使用给定 String 中的字符替换此序列的子字符串中的字符。
void setCharAt(int index,char ch): 将给定索引处的字符设置为 ch。
5.反转
StringBuffer reverse() :将此字符序列用其反转形式取代。
6.将缓冲区中指定数据存储到指定数组中
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) :将字符从此序列复制到目标字符数组 dst。
- /*
- StringBuffer常见功能操作:
- */
- class StringBufferDemo
- {
- public static void main(String[] args)
- {
- method_add();//添加
- method_del();//删除
- method_update();//修改
- method_select();//获取
- }
- public static void method_add()
- {
- sop("添加:");
- StringBuffer sb=new StringBuffer();
- sb.append(23).append(true).append(78);
- sb.insert(1,"qq");
- sop(sb.toString());
- }
- public static void method_del()
- {
- sop("删除:");
- StringBuffer sb=new StringBuffer("abcdefg");
- sb.delete(1,3);
- sop(sb.toString());
- //sb.delete(0,sb.length());//清空缓冲区
- sb.deleteCharAt(2);
- sop(sb.toString());
- }
- public static void method_update()
- {
- sop("修改:");
- StringBuffer sb=new StringBuffer("abcdefg");
- sb.replace(1,4,"java");
- sop(sb.toString());
- sb.setCharAt(2,'x');
- }
- public static void method_select()
- {
- sop("获取");
- StringBuffer sb=new StringBuffer("abcdefg");
- sop(sb.substring(2,4));
- }
- public static void sop(String str)
- {
- System.out.println(str);
- }
- }
五、StringBuilder
JDK1.5版本以后出现了StringBuilder
StringBuffer:线程同步。
StringBuilder:线程不同步。
以后开发建议使用StringBuilder。
六、基本数据类型对象包装类
byte Byte
short Short
int Integer
long Long
boolean Boolean
float Float
double Double
char Character
基本数据类型对象包装类的最常见作用:
用于基本数据类型和字符串类型之间做转换。
基本数据类型转成字符串:
基本数据类型+""
基本数据类型.toString(基本数据类型值);
如:Integer.toString(32);//将32整数变成"32"
字符串转成基本数据类型:
xxx a= Xxx.parseXxx(String);
例如:
int a=Integer.parseInt("123");
double d= double.parseDouble("12.23");
boolean b=Boolean.pareseBoolean("true");
char c=Character.toLowerCase('A');
也可以封装Integer 对象。
Integer num=new Integer("123");
int n=num.intValue();
十进制转换为其它进制:
toBinaryString();
toHexString();
toOctalString();
其它进制转换为十进制:
parseInt(string,radix): radix: 2代表二进制。8代表八进制。16代表十六进制。
七、基本数据类型对象包装类新特性
- /*
- JDK1.5版本以后出现的新特性:
- */
- class IntegerDemo1
- {
- public static void main(String[] args)
- {
- //Integer x=new Integer(4);
- Integer x=4;//自动装箱 new Integer(4)
- sop("x="+x);
- x=x+2;/*x=2 x进行自动拆箱,变成了int 类型和2进行加法运算,再将
- 和进行装箱赋值给x
- x=x.intValue()+2
- 如果x=null;
- x.intValue()时会抛出Runtime异常。
- */
- sop("x+2="+x);
- Integer m=128;
- Integer n=128;
- sop("m==n:"+(m==n));
- Integer a=127;
- Integer b=127;
- sop("a==b:"+(a==b));/*结果为true。因为a和b指向了同一个Integer对象。
- 当数值在byte范围内时,对于新特性,如果数值已经存在
- 则不会再开辟新的空间。
- */
- method();
- }
- public static void method()
- {
- Integer x=new Integer("123");
- Integer y=new Integer(123);
- sop("x==y:"+(x==y));
- sop("x.equals(y):"+x.equals(y));
- }
- public static void sop(String str)
- {
- System.out.println(str);
- }
- }