黑马程序员10.String&StringBuffer

来源:互联网 发布:人工智能ai 下载 编辑:程序博客网 时间:2024/05/22 01:52

-------android培训java培训java学习型技术博客、期待与您交流! ---------- 

今天学习了毕老师java基础第13天的内容,在这里总结一下。

String

String概述

java lang 包中有String类:

被final定义,代表不能有子类。操作字符串的功能是不能复写的。

class StringDemo {public static void main(String[] args) {//下面两行代码是一回事String s = new String("abc");String s1 = "abc";//一般用这种,简单。s1是一个类类型变量,"abc"是一个对象。字符串最大特点:一旦被初始化就不可以被改变。}}

class  StringDemo{public static void main(String[] args) {String s1 = "abc";s1="kk";System.out.println(s1);}}
结果:

abc没变,s1变了,指向了另外一个对象,abc这个对象还在内存中。

class  StringDemo{public static void main(String[] args) {String s1 = "abc";String s2 = new String("abc");System.out.println(s1==s2);System.out.println(s1.equals(s2));}}
结果:


s1和s2是两个对象,所以第一个结果是false,Object类中equals()方法是比较地址值,String类中复写了这个方法,用于判断字符串是否相同。

s1和s2的区别:
s1在内存中有一个对象,s2有两个对象。 String s2 = new String("abc"); new创建了一个对象,"abc"是一个对象

class  StringDemo{public static void main(String[] args) {String s1 = "abc";String s2 = new String("abc");String s3 = "abc";System.out.println(s1==s2);System.out.println(s1==s3);}}
结果:
 
“abc”字符串对象已经在内存中存在了,s3在初始化的时候发现已经存在了它就不会再独立开辟空间了。s1,s3指向了同一个对象。

常见功能-获取和判断

String类适用于描述字符串事物。
那么它就提供了多个方法对字符串进行操作。

常见的操作 

1.获取

1.1 字符串中的包含的字符数,也就是字符串的长度。
int length():获取长度。
class  StringMethodDemo{public static void method_get(){String str = "abcdef"; //长度sop(str.length());}public static void main(String[] args) {method_get();}public static void sop(Object obj){System.out.println(obj);}}


1.2 根据位置获取位置上某个字符。
char charAt(int index):
1.3 根据字符获取该字符在字符串中位置。
int indexOf(int ch):返回的是ch在字符串中第一次出现的位置。接收的是ASCII码。
int indexOf(int ch, int fromIndex) :从fromIndex指定位置开始,获取ch在字符串中出现的位置。

int indexOf(String str):返回的是str在字符串中第一次出现的位置。
int indexOf(String str, int fromIndex) :从fromIndex指定位置开始,获取str在字符串中出现的位置。
class  StringMethodDemo{public static void method_get(){String str = "abcdeakpf"; //长度sop(str.length());//根据索引获取字符。sop(str.charAt(4));//当访问到字符串中不存在的角标时会发生StringIndexOutOfBoundsException。//根据字符获取索引sop(str.indexOf('a'));//如果没有找到,返回-1.}public static void main(String[] args) {method_get();}public static void sop(Object obj){System.out.println(obj);}}


反向索引:
int lastIndexOf(int ch) :从右往左开始查找

2.判断

2.1 字符串中是否包含某一个子串。
boolean contains(str):
特殊之处:indexOf(str):可以索引str第一次出现位置,如果返回-1.表示该str不在字符串中存在。
    所以,也可以用于对指定判断是否包含。
    if(str.indexOf("aa")!=-1)
    而且该方法既可以判断,又可以获取出现的位置。
2.2 字符中是否有内容。
boolean isEmpty(): 原理就是判断长度是否为0. 
1.6版本开始提供。
“”和null是有区别的""是指向对象,null是空
2.3 字符串是否是以指定内容开头。
boolean startsWith(str);
2.4 字符串是否是以指定内容结尾。
boolean endsWith(str);
public static void method_get(){String str = "ArrayDemo.java";//判断文件名称是否是Array单词开头。sop(str.startsWith("Array"));//判断文件名称是否是.java的文件。sop(str.endsWith(".java"));//判断文件中是否包含Demosop(str.contains("Demo"));}public static void main(String[] args) {  method_is();}


2.5 判断字符串内容是否相同。复写了Object类中的equals方法。
boolean equals(str);
2.6 判断内容是否相同,并忽略大小写。
boolean equalsIgnoreCase();


3.转换

3.1 将字符数组转成字符串。
构造函数:String(char[] value)
    String(char[] value, int offset,int count):将字符数组中的一部分转成字符串。
静态方法:
static String copyValueOf(char[]);
static String copyValueOf(char[] data, int offset, int count) 
static String valueOf(char[]):
public static void method_trans(){char [] arr = {'a','b','c','d','e','f'};String s = new String(arr);sop("s="+s);}public static void main(String[] args) {  method_trans();}
public static void method_trans(){char [] arr = {'a','b','c','d','e','f'};String s = new String(arr,1,3);sop("s="+s);}public static void main(String[] args) {  method_trans();}

3是个数。

3.2 将字符串转成字符数组。**
char[] toCharArray():
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 = "zxcvbnm";char[] chs = s1.toCharArray();for (int x=0;x<chs.length ;x++ ){sop("ch="+chs[x]);}}


3.3 将字节数组转成字符串。
String(byte[])
String(byte[],offset,count):将字节数组中的一部分转成字符串。
3.4 将字符串转成字节数组。
byte[]  getBytes():
3.5 将基本数据类型转成字符串。
static String valueOf(int)
static String valueOf(double)
//3+"";//String.valueOf(3);

特殊:字符串和字节数组在转换过程中,是可以指定编码表的。

4.替换

String replace(char oldchar,char newchar);
public static void method_replace(){String s = "hello java";String s1 = s.replace('a','n');//如果要替换的字符不存在,返回的还是原串。        //String s1 = s.replace("java","world"); 还可以替换字符串sop("s="+s);sop("s1="+s1);}public static void main(String[] args) {  method_replace();}
字符串一旦建立不能改变,这有两个字符串:


5,切割

String[] split(regex);
public static void method_split(){String s = "zhagnsa,lisi,wangwu";String[] arr  = s.split(",");for(int x = 0; x<arr.length; x++){sop(arr[x]);}}}public static void main(String[] args) {  method_split();}


6,子串。获取字符串中的一部分

String substring(begin);
String substring(begin,end);
public static void method_sub(){String s = "abcdef";sop(s.subString(2));//从指定位置开始到结尾。如果角标不存在,会出现字符串角标越界异常。sop(s.subString(2,4));//包含头,不包含尾。s.substring(0,s.length());}public static void main(String[] args) {  method_sub();}

7,转换,去除空格,比较

7.1 将字符串转成大写或则小写
String toUpperCase();
String toLowerCase();
public static void method_7(){String s = "     Hello Java     ";sop(s.toLowerCase());sop(s.toUpperCase());sop(s.trim());}public static void main(String[] args) {  method_7();}


7.2 将字符串两端的多个空格去除
String trim();
7.3 对两个字符串进行自然顺序的比较
int compareTo(string);
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 main(String[] args) {  method_7();}



练习

练习1

1,模拟一个trim方法,去除字符串两端的空格。
思路:
1,判断字符串第一个位置是否是空格,如果是继续向下判断,直到不是空格为止。
结尾处判断空格也是如此。
2,当开始和结尾都判断到不是空格时,就是要获取的字符串。
class StringTest{public static void sop(String str){System.out.println(str);}public static void main(String[] args){String s = "       ab cd         ";sop("("+s+")");s = myTrim(s);sop("("+s+")");}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);}}




练习2

2,将一个字符串进行反转。将字符串中指定部分进行反转,"abcdefg";abfedcg
思路:
1,曾经学习过对数组的元素进行反转。
2,将字符串变成数组,对数组反转。
3,将反转后的数组变成字符串。
4,只要将或反转的部分的开始和结束位置作为参数传递即可。
class StringTest2{public static void sop(String str){System.out.println(str);}public static void main(String[] args){String s = "      ab cd      ";sop("("+s+")");sop("("+reverseString(s)+")");}public static String reverseString(String s){//字符串变数组。char[] chs = s.toCharArray();//反转数组。reverse(chs);//将数组变成字符串。return new String(chs);}private static void reverse(char[] arr){for (int start=0,edd=arr.length-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;}}


只换ab:
class StringTest2{public static void sop(String str){System.out.println(str);}public static void main(String[] args){String s = "      ab cd      ";sop("("+s+")");sop("("+reverseString(s,6,7)+")");}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,edd=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;}}

整个反转就是start=0,end=str.length().

练习3

3,获取一个字符串在另一个字符串中出现的次数。
"abkkcdkkefkkskk"
思路:
1,定义个计数器。
2,获取kk第一次出现的位置。
3,从第一次出现位置后剩余的字符串中继续获取kk出现的位置。
每获取一次就计数一次。
4,当获取不到时,计数完成。
class  StringTest3{/*练习三。*/public static int getSubCount(String str,String key){int count = 0;int index = 0;while((index=str.indexOf(key))!=-1){sop("str="+str);str = str.substring(index+key.length());count++;}return count;}/*练习三,方式二。*/public static int getSubCount_2(String str,String key){int count = 0;int index = 0;while((index= str.indexOf(key,index))!=-1){sop("index="+index);index = index + key.length();count++;}return count;}public static void main(String[] args) {String str = "kkabkkcdkkefkks";///sop("count====="+str.split("kk").length);不建议使用。sop("count="+getSubCount_2(str,"kk"));}public static void sop(String str){System.out.println(str);}}

练习4

4,获取两个字符串中最大相同子串。第一个动作:将短的那个串进行长度一次递减的子串打印。
"abcwerthelloyuiodef"
"cvhellobnm"
思路:
1,将短的那个子串按照长度递减的方式获取到。
2,将每获取到的子串去长串中判断是否包含,
如果包含,已经找到!。
class  StringTest4{/*练习四。*/public static String getMaxSubString(String s1,String s2){String max = "",min = "";max = (s1.length()>s2.length())?s1: s2;min = (max==s1)?s2: s1;//sop("max="+max+"...min="+min);for(int x=0; x<min.length(); x++){for(int y=0,z=min.length()-x; z!=min.length()+1; y++,z++){String temp = min.substring(y,z);sop(temp);if(max.contains(temp))//if(s1.indexOf(temp)!=-1)return temp;}}return "";}public static void main(String[] args) {String s1 = "ab";String s2 = "cvhellobnm";sop(getMaxSubString(s2,s1));}public static void sop(String str){System.out.println(str);}}

StringBuffer

StringBuffer是字符串缓冲区。

是一个容器。
特点:
1,长度是可变化的。
2,可以字节操作多个数据类型。
3,最终会通过toString方法变成字符串。
C create U update R read D delete

1,存储。
StringBuffer append():将指定数据作为参数添加到已有数据结尾处。
StringBuffer insert(index,数据):可以将数据插入到指定index位置。
2,删除。
StringBuffer delete(start,end):删除缓冲区中的数据,包含start,不包含end。
StringBuffer deleteCharAt(index):删除指定位置的字符。
3,获取。
char charAt(int index) 
int indexOf(String str) 
int lastIndexOf(String str) 
int length() 
String substring(int start, int end) 
4,修改。
StringBuffer replace(start,end,string);
void setCharAt(int index, char ch) ;
5,反转。
StringBuffer reverse();
6,
将缓冲区中指定数据存储到指定字符数组中。
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) 
JDK1.5 版本之后出现了StringBuilder.
StringBuffer是线程同步。
StringBuilder是线程不同步。
以后开发,建议使用StringBuilder
升级三个因素:
1,提高效率。
2,简化书写。
3,提高安全性。


基本数据类型对象包装类

基本数据类型对象包装类。


byte Byte
short Short
int Integer
long Long
boolean Boolean
float Float
double Double
char Character
class IntegerDemo {public static void sop(String str){System.out.println(str);}public static void main(String[] args) {//整数类型的最大值。//sop("int max :"+Integer.MAX_VALUE);//将一个字符串转成整数。int num = Integer.parseInt("123");//必须传入数字格式的字符串。//long x = Long.parseLong("123");//sop("num="+(num+4));//sop(Integer.toBinaryString(-6));//sop(Integer.toHexString(60));int x = Integer.parseInt("3c",16);sop("x="+x);}}
基本数据类型对象包装类的最常见作用,
就是用于基本数据类型和字符串类型之间做转换


基本数据类型转成字符串。


基本数据类型+""


基本数据类型.toString(基本数据类型值);


如: Integer.toString(34);//将34整数变成"34";




字符串转成基本数据类型。


xxx a = Xxx.parseXxx(String);


int a = Integer.parseInt("123");


double b = Double.parseDouble("12.23");


boolean b = Boolean.parseBoolean("true");


Integer i = new Integer("123");


int num = i.intValue();







十进制转成其他进制。
toBinaryString();
toHexString();
toOctalString();




其他进制转成十进制。
parseInt(string,radix);
class IntegerDemo {public static void sop(String str){System.out.println(str);}public static void main(String[] args) {//整数类型的最大值。//sop("int max :"+Integer.MAX_VALUE);//将一个字符串转成整数。int num = Integer.parseInt("123");//必须传入数字格式的字符串。//long x = Long.parseLong("123");//sop("num="+(num+4));//sop(Integer.toBinaryString(-6));//sop(Integer.toHexString(60));int x = Integer.parseInt("3c",16);sop("x="+x);}}

新特性
/*JDK1.5版本以后出现的新特性。*/class IntegerDemo1 {public static void main(String[] args) {//Integer x = new Integer(4);Integer x = 4;//自动装箱。//4等同于new Integer(4)是个对象,简化书写 Integer x 可以取null 要判断,否则会出异常。x = x/* x.intValue() */ + 2;//x+2:x 进行自动拆箱。变成成了int类型。和2进行加法运算。//再将和进行装箱赋给x。Integer m = 128;Integer n = 128;sop("m==n:"+(m==n));//两个对象,所以为falseInteger a = 127;Integer b = 127;sop("a==b:"+(a==b));//结果为true。因为a和b指向了同一个Integer对象。//因为当数值在byte范围内时,对于新特性,如果该数值已经存在,则不会在开辟新的空间。}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);}}


-------android培训java培训java学习型技术博客、期待与您交流! ---------- 
0 0
原创粉丝点击