目录
Scanner:
1、Scanner:
(1)键盘录入工具,通过观察API发现,该类方法没有被static修饰,所以需要创建对象去使 用,因此了解一下关于Scanner的构造方法
(2)Scanner的构造方法:
public Scanner(InputStream source):构造一个新的Scanner(3)API解释:产生从指定的输入流扫描的值,流中的字节将使用底层平台的dafault charset 转换为字符,Java默认使用的编码是Unicode 万国码
(4)参数:InputStream source:InputStream指的是字节流类型、
简单理解为从键盘录入的数据
(5)之前提到过:对于录入字符串类型的数据有两种方式:next(),nextLine()
public String next():查找并返回此扫描仪的下一个完整令牌
public String nextLine():将此扫描仪推进到当前行并返回跳过的输入
nextLine可以接收一些特殊字符,如换行符:\r\n,\n,\t等
String字符串:
2、字符串:
简单理解为:由一个签字将若干个字符串起来的串儿,叫字符串
官方理解: 字符串是由多个字符组成的一串数据(字符序列)
字符串可以看成是字符数组 !!!!!通过观察API发现:
(1)String代表的是字符串。属于java.lang包下,所以在使用的时候不需要导包
(2)String类代表字符串。 Java程序中的所有字符串文字(例如"abc" )都被实现为此类 的实例。(对象3
(3)字符串不变; 它们的值在创建后不能被更改。
字符串是常量,一旦被赋值,字符串本身不能被修改。
3、构造方法:
public String()
public String(byte[] bytes)
public String(byte[] bytes,int offset,int length)
public String(char[] value)
public String(char[] value,int offset,int count)
public String(String original)===============================================
public String():无参构造方法
public String(byte[] bytes):
根据一个字节数组创建出一个字符串对象
public String(byte[] bytes,int offset,int length):
将字节数组中的一部分转化为字符串,从index索引处开始,长度为length的部分
public String(char[] value):
将字符数组转成一个字符串
public Stirng(char[] value,int index,int length):
将字符数组的一部分转成字符串,从index索引处开始,长度为length的部分
当转换的长度超过实际在数组中转换的长度时
报错:字符索引越界异常:StringIndexOutOfBoundsException
public String(String original):初始化新创建的字符串
public class StringDemo1 { public static void main(String[] args) { //public String() String s = new String(); System.out.println(s); //String类中重写toString()方法 //查看字符串的长度 //public int length()返回此字符串的长度。 System.out.println("字符串s的长度为:" + s.length()); //如果字符串中没有字符,返回0 System.out.println("====================================================="); //public String(byte[] bytes) //根据一个字节数组创建出一个字符串对象 byte[] bytes = {97, 98, 99, 100, 101}; String s2 = new String(bytes); System.out.println("s2: " + s2); System.out.println("字符串s2的长度为:" + s2.length()); System.out.println("====================================================="); //public String(byte[] bytes,int index,int length) //将字节数组中的一部分转化成字符串 String s3 = new String(bytes, 1, 3); System.out.println("s3: " + s3); System.out.println("字符串s3的长度为:" + s3.length()); System.out.println("====================================================="); //public String(char[] value) //将字符数组转成一个字符串 char[] c = {'a', 'b', 'c', 'd', '我', '爱', '冯', '提', '莫'}; String s4 = new String(c); System.out.println("s4: " + s4); System.out.println("字符串s4的长度为:" + s4.length()); System.out.println("====================================================="); //public String(char[] value,int index,int length) //将字符数组的一部分转成字符串 String s5 = new String(c, 4, 5); System.out.println("s5: " + s5); System.out.println("字符串s5的长度为:" + s5.length()); System.out.println("====================================================="); //StringIndexOutOfBoundsException // String s6 = new String(c,4,10); // System.out.println("s6: "+s6); // System.out.println("字符串s5的长度为:" + s6.length()); System.out.println("====================================================="); //public String(String original) String s7 = "你好"; String s8 = new String(s7); System.out.println("s8: " + s8); System.out.println("字符串s8的长度为:" + s8.length()); } }
运算结果:
5、 字符串的拼接与常量池 :
(1) 字符串是常量,它的值在创建后不能被改变
String s = "hello";
s += "world";
请问s的值是什么?public class StringDemo2 { public static void main(String[] args) { String s = "hello"; s += "world"; System.out.println(s); } }
运行结果:
重点概述:
字符串一旦被创建就不能被改变。
不能改变指的是字符串在常量池中的值不能被改变。
解释:
当对s进行初始化时,先在常量池中开辟一处空间,存放hello字符串,再将该空间的地址值赋值给栈内存中的s,
当进行s+="world"操作时,JVM会先在常量池中查找是否有world字符串,没有则会在常量池中再开辟一块空间用于存放world。
在进行+操作时会先将hello与world做字符串拼接,再在常量池中寻找是否有helloworld字符串,没有则再开辟另外的一个空间存放helloworld,最后将helloworl的地址值赋值给s,自始至终,常量池中的值始终没有改变。
图解:
(2) String s = new String(“hello”)和String s = “hello”;的区别?
字符串比较之看程序写结果
字符串拼接之看程序写结果注意事项:
a、==比较引用数据类型的时候,比较的时候地址值
b、String类中使用equals方法比较的是字符串的值,因为String类中重写了equals方法在字符串中使用==与equals案例:
public class StringDemo4 { public static void main(String[] args) { String s1 = new String("hello"); String s2 = new String("hello"); System.out.println(s1==s2); // false System.out.println(s1.equals(s2)); // true String s3 = new String("hello"); String s4 = "hello"; System.out.println(s3==s4);// false System.out.println(s3.equals(s4)); // true String s5 = "hello"; String s6 = "hello"; System.out.println(s5==s6); // true System.out.println(s5.equals(s6)); // true } }
对于常量池中的地址的比较:
public class Test2 { public static void main(String[] args) { String s1="hello"; String s2="java"; String s3="hello"+"java"; String s4="hellojava"; System.out.println(s3==s4);//true System.out.println(s3==(s1+s2));//false String s5=s1+s2; System.out.println(s4==s5);//false System.out.println(s3==s5);//false String s6=new String("hellojava"); System.out.println(s3==s6);//false System.out.println(s4==s6);//false /* 对于s6的解释为: S6是在堆内存中创建了一个空间赋给了s6, 对象的位置完全不同,地址值一定和常量池中的地址值不同 */ } }
结论:
1、字符串如果是变量相加,是先在常量池中开辟两个变量相加的空间,然后再把做字符串拼接后的结果存放到该空间中。(先开辟空间,再拼接)
2、字符串如果是常量相加,是先做字符串拼接,再根据拼接后的结果去常量池中寻找是否有该结果,如果没有,则开辟新空间存放该结果。(先拼接,再开辟空间)
6、 String类的判断功能:
boolean equals(Object obj):
比较字符串内容是否相同,区分大小写比较
boolean equalsIgnoreCase(String str):
比较字符串内容是否相同,不区分大小写比较
boolean contains(String str):
判断大字符串中是否包含小字符串,包含返回true,不包含返回false
boolean startWith(String str):
判断此字符串是否以指定字符串开头,区分大小写
boolean endWith(String str):
判断此字符串是否以指定字符串结尾,区分大小写
boolean isempty():
判断字符串是否是空字符串,是空字符串返回true,不是返回false
举例说明:
public class StringDemo6 { public static void main(String[] args) { String s1 = "helloworld"; String s2 = "Helloworld"; String s3 = "HelloWorld"; //boolean equals(Object obj)比较字符串中的内容是否相同,区分大小写比较的 System.out.println(s1.equals(s2)); System.out.println(s1.equals(s3)); System.out.println("********************************"); //boolean equalsIgnoreCase(String str)比较字符串中的内容是否相同,忽略大小写 System.out.println(s1.equalsIgnoreCase(s2)); System.out.println(s1.equalsIgnoreCase(s3)); System.out.println("********************************"); //boolean contains(String str) //判断大的字符串中是否包含小的字符串,如果包含,返回true,反之返回false //区分大小写 System.out.println(s1.contains("Hello")); //false System.out.println(s1.contains("hel")); System.out.println(s1.contains("owo")); System.out.println("********************************"); //boolean startsWith(String str) //测试此字符串是否以指定字符串开头 //区分大小写 System.out.println(s1.startsWith("hel")); System.out.println(s1.startsWith("Hel")); // false System.out.println(s1.startsWith("hell34")); // false System.out.println("********************************"); //boolean endsWith(String str) //测试此字符串是否以指定字符串结尾 //区分大小写 System.out.println(s1.endsWith("rld")); System.out.println(s1.endsWith("rlD")); System.out.println("********************************"); //boolean isEmpty() //判断字符串是否是空字符串 System.out.println(s1.isEmpty()); System.out.println("********************************");
特殊举例:
当字符串为空字符串时,定义为:String s = "";
但是当字符串为空时,定义为:String s = null;
这两种定义不一样,第一种是有字符串,但是字符串内容为空字符串;第二种是没有字符串内容。
案例说明:
public class Test3 { public static void main(String[] args) { String s1=""; String s2=null; System.out.println(s1==s2);//false System.out.println(s2==s1);//false System.out.println(s1.equals(s2));//false // System.out.println(s2.equals(s1)); } }
最后一行注释如果不注释会报错:NullPointerException:空指针异常
注意:在做字符串比较时,很容易出现空指针异常,这是由于前面调用方法的变量可能是null值,从而导致无法正常调用方法。
为了避免这种情况,在比较之前加入一个判断,判断前面调用方法的变量是否为null
若是变量一与常量作比较,则可以把常量放在前面,单独一个字符串也是一个String对象
public class Test3 { public static void main(String[] args) { String s1=""; String s2=null; System.out.println(s1==s2);//false System.out.println(s2==s1);//false System.out.println(s1.equals(s2));//false // System.out.println(s2.equals(s1)); // 加入判断: String s6 = null; String s7 = "hello"; if(s6!=null){ if(s6.equals(s7)){ System.out.println("是一样的"); } }else { System.out.println("s6是null值"); } } }
7、String类的获取功能:
int length():
char charAt(int index):
int indexOf(int ch):
int indexOf(String str):
int indexOf(int ch,int fromIndex):
int indexOf(String str,int fromIndex):
String substring(int start):
String substring(int start,int end):
举例说明:
public class StringDemo7 {
public static void main(String[] args) {
String s = "helloworld";
//int length() 获取字符串的长度
System.out.println("字符串s的长度为:"+s.length());
System.out.println("==================================");
//char charAt(int index) 返回指定索引处的字符
//0<=index<=length()-1
System.out.println(s.charAt(4));//o
System.out.println(s.charAt(0));//h
//StringIndexOutOfBoundsException
// System.out.println(s.charAt(100));
System.out.println(s.charAt(9));//d
System.out.println("==================================");
//public int indexOf(int ch)返回指定字符第一次出现的字符串内的索引。
//需求:获取o在字符串中第一次出现的位置
System.out.println(s.indexOf('o'));//4
//如果此字符串中没有此类字符,则返回-1 。
System.out.println(s.indexOf(97));//-1
System.out.println("==================================");
//public int indexOf(String str)返回指定子字符串第一次出现的字符串内的索引。
//返回的是小串的第一个字符在大串中出现的索引位置
//owo
System.out.println(s.indexOf("owo"));//4
//如果大串中不存在小串,返回-1
System.out.println(s.indexOf("owe"));//-1
System.out.println(s.indexOf("qwer"));//-1
System.out.println("==================================");
// public int indexOf(int ch,int fromIndex)
// 返回指定字符第一次出现的字符串内的索引,以指定的索引开始搜索。
//如果找到了,返回的是字符在整个字符串中的索引
System.out.println(s.indexOf("l",4)); // 8
System.out.println(s.indexOf("l",1000)); // -1
System.out.println(s.indexOf("p",4)); // -1
System.out.println(s.indexOf("p",1000)); // -1
System.out.println("==================================");
// int indexOf(String str,int fromIndex)
System.out.println("==================================");
//helloworld
// String substring(int start) 从指定位置处截取字符串,包括开始截取的位置,截取到末尾
//如果给的索引值不存在,报错
System.out.println(s.substring(3)); // loworld
// System.out.println(s.substring(100)); // StringIndexOutOfBoundsException
System.out.println("==================================");
//String substring(int start,int end)
//截取字符串的一部分出来
//截取的串从start位置开始截取,截取到end-1的位置结束
//左闭右开 [,) 含头不含尾。
System.out.println(s.substring(5,8)); // wor
// System.out.println(s.substring(1,20)); //StringIndexOutOfBoundsException
}
}
8、 String类的转换功能:
byte[] getBytes():
将字符串转换为字节数组
char[] toCharArray():
将字符串转换为字符数组
static String valueOf(char[] chs):
将字符数组转换为字符串
static String valueOf(int i):
将字节数组转换为字符串
String toLowerCase():
将字符串中的内容全部转小写
String toUpperCase():
将字符串中的内容全部转大写
String concat(String str):将括号中的str字符串拼接到大字符串后面
public String[] split(String regex) :获取字符串中以regex分割的每个子字符串
举例说明:
public class StringDemo8 {
public static void main(String[] args) {
String s = "HelloWorLD";
// public byte[] getBytes()使用平台的默认字符集将此String编码为字节序列,
// 将结果存储到新的字节数组中。
//将字符串转成字节数组
byte[] bytes = s.getBytes();
// System.out.println(bytes);
for(int i=0;i<bytes.length;i++){
System.out.print(bytes[i]);
}
//72 101 108 108 111 87 111 114 76 68
System.out.println();
System.out.println("=================================");
//char[] toCharArray()
//将字符串转成字符数组
char[] chars = s.toCharArray();
for(int i=0;i<chars.length;i++){
System.out.println(chars[i]);
}
//增强for循环,后面上到集合的时候会讲解
// for(char c : chars){
// System.out.println(c);
// }
System.out.println("=================================");
//static String valueOf(char[] chs)
//将字符数组转成字符串
String s1 = String.valueOf(chars);
System.out.println(s1);
System.out.println("=================================");
//static String valueOf(int i) 数据库
//将int类型的数据转成字符串
String s2 = String.valueOf(100); // 100 --> "100"
System.out.println(s2); //100
System.out.println("=================================");
//String toLowerCase()
//将字符串中的内容全部转小写
String s3 = s.toLowerCase();
System.out.println(s3); //helloworld
System.out.println("=================================");
//String toUpperCase()
String s4 = s.toUpperCase();
System.out.println(s4); //HELLOWORLD
System.out.println("=================================");
//String concat(String str)
//将小括号中str的字符串拼接到大字符串的后面
String s5 = s.concat("hadoop");
System.out.println(s5);//HelloWorLDhadoop
System.out.println("=================================");
//public String[] split(String s)
String s6 = "hello world hello java world";
//需求:求出字符串中的每一个单词
String[] strings = s6.split(" ");
for(int i=0;i<strings.length;i++){
System.out.println(strings[i]);
}
}
}
9、String类的其他功能:
替换功能
String replace(char old,char new)
String replace(String old,String new)
去除字符串左右两边的空格
String trim()
按字典顺序比较两个字符串
int compareTo(String str)
int compareToIgnoreCase(String str)
举例说明:
public class StringDemo9 {
public static void main(String[] args) {
String s = "hellowrodldajavahadoopowollohelloowo";
//String replace(char old,char new)
//将新的字符串替换字符串中指定的所有字符,并返回一个替换后的字符串
String s1 = s.replace('l', 'q');
System.out.println(s);
System.out.println(s1);
System.out.println("====================================");
//String replace(String old,String new)
//将字符串中就的小串用新的小串替换,返回一个替换后的字符串
String s2 = s.replace("owo", "===");
System.out.println(s);
System.out.println(s2);
System.out.println();
String s3 = s.replace("owo", "@@@@");
System.out.println(s);
System.out.println(s3);
System.out.println();
//如果被替换的字符串不存在会是什么情况呢?返回的是原本的字符串
String s4 = s.replace("qwer", "LOL");
System.out.println(s);
System.out.println(s4);
System.out.println("====================================");
//String trim() 去除字符串两边的若干个空格
String s5 = " hello world ";
System.out.println(s5);
System.out.println(s5.trim());
System.out.println("====================================");
//int compareTo(String str) //比较字符串是否相同,如果相同返回0
String s6 = "hello"; // h的ASCII码值是 104
String s7 = "hello";
String s8 = "abc"; // a的ASCII码值是 97
String s9 = "qwe"; // q的ASCII码值是 113
System.out.println(s6.compareTo(s7)); // 0
System.out.println(s6.compareTo(s8)); // 7
System.out.println(s6.compareTo(s9)); // -9
String s10 = "hel";
System.out.println(s6.compareTo(s10)); // 2
}
}
特殊说明:
调用compareTo方法的结果的缘由:
compareTo方法的逻辑需要去源码中查看:
compareTo的源码:
public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}
代码解释:如果两个字符串的长度不一样,当长度较短的字符串的每个字符比较完之后,如果前面几个字符都和长字符串相同,则返回两个字符串的长度差值,如果在比较字符的过程中有一个字符不同,则返回两个字符的ASCII码的差值。
练习:
一、获取大小写字符个数,以及数字字符个数:
1、遍历获取字符串中的每一个字符
2:统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)
解决方法:
public class StringTest1 {
public static void main(String[] args) {
String s = "javaMySqlHadoopHive12138";
//遍历获取字符串中的每一个字符
//将字符串转成字符数组
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
System.out.println(chars[i]);
}
System.out.println("=================================================");
//统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)
//1、定义三个变量统计三个结果
int bigCount = 0;
int smallCount = 0;
int numberCount = 0;
//2、遍历字符数组得到每一个字符,判断每一个字符是属于哪一类
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (c >= 'A' && c <= 'Z') {
bigCount++;
} else if (c >= 'a' && c <= 'z') {
smallCount++;
} else if (c >= '0' && c <= '9') {
numberCount++;
}
}
System.out.println("大写字符的个数为:" + bigCount);
System.out.println("小写字符的个数为:" + smallCount);
System.out.println("数字字符的个数为:" + numberCount);
}
}
使用String类中的CharAt方法解决该问题:大致实现部分相同,不同之处在于代码中对于每个字符判断所用的方法不一致:
for(int i=0;i<line.length();i++){
char s=line.charAt(i);//按顺序每次获取字符串的一个字符
if(s>='A'&& s<='Z'){
bigcount++;//大写字母
}else if(s>='a' && s<='z'){
smallcount++;//小写字母
}else if(s>='0' && s<='9'){
numbercount++;//数字
}
}
结果一致:
二、字符串大小写之间的转换例题:
把一个字符串的首字母转成大写,其余为小写。(只考虑英文大小写字母字符)
举例:"hADoopJava" --> "Hadoopjava"
1、全部转小写
2、获取第一个字符转大写
具体实现: 1、截取第一个字符和其他字符 2、第一个字符转大写 3、其他字符转小写 4、拼接
具体代码实现:
public class StringTest2 {
public static void main(String[] args) {
String s = "hADoopJava";
System.out.println("转换之前:" + s);
//将字符串中的所有字符全部转小写
String s1 = s.toLowerCase();
//获取第一个字符
// char s2 = s1.charAt(0);
String s2 = s1.substring(0, 1);
//将第一个字符转大写
String s3 = s2.toUpperCase();
//获取除第一个字符以外的其他字符
String s4 = s1.substring(1);
//将转大写的字符与其余的字符做拼接
String result = s3.concat(s4);
System.out.println("转换之后:" + result);
System.out.println("==================用链式编程转换==================");
String result2 = s.substring(0, 1)
.toUpperCase()
.concat(s.substring(1).toLowerCase());
System.out.println("转换之后:" + result2);
}
}
结果:
三、数组数据做字符串拼接:
把数组中的数据按照指定个格式拼接成一个字符串
举例:int[] arr = {1,2,3}; 输出结果:[1, 2, 3]
实现:
public class StringTest3 {
public static void main(String[] args) {
int[] arr = {1,2,3};
String s = "";
for(int i=0;i<arr.length;i++){
String s1 = String.valueOf(arr[i]);
if(i==0){
System.out.print(s.concat("[").concat(s1).concat(","));
}else if(i==arr.length-1){
System.out.print(s.concat(s1).concat("]"));
}else {
System.out.print(s.concat(s1).concat(","));
}
}
System.out.println(s);
}
}
结果:
四、字符串反转:
举例:键盘录入”abc” 输出结果:”cba”
分析: 1、导包并创建键盘录入对象 2、创建一个空的字符串 3、将字符串转成字符数组 4、倒着遍历,得到每一个字符 5、将每次获取到的字符进行拼接 6、输出
代码实现:
import java.util.Scanner;
public class StringTest4 {
public static void main(String[] args) {
//创建键盘录入对象
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String s = sc.next();
//创建一个空的字符串
String s1 = "";
//将字符串转成字符数组
char[] chars = s.toCharArray();
//倒着遍历,得到每一个字符
for (int i = chars.length - 1; i >= 0; i--) {
//将每个字符转成字符串
String s2 = String.valueOf(chars[i]);
// System.out.println(s2);
//将每次获取到的字符进行拼接
s1 = s1.concat(s2);
}
System.out.println("倒序后的字符串为:" + s1);
}
}
结果:
五、统计大串中出现小串的次数:
举例:在字符串"woaijavawozhenaijavawozhendeaijavawozhende"中java出现了三次
代码实现:
public class StringTest5 {
public static void main(String[] args) {
//创建一个字符串
String bigString ="woaijavawozhenaijavawozhendeaijavawozhende";
// 定义要查找的小串:java
String minString = "java";
//定义一个变量统计小串出现的次数
int count = 0;
//在大串中找到小串第一次出现的位置
int index = bigString.indexOf(minString);
//也有可能第一次找的时候就没有找到
if (index == -1) {
System.out.println("该大串中没有小串" + minString);
} else {
while (index != -1) {
count++;
//截取字符串
int startIndex = index + minString.length();
bigString = bigString.substring(startIndex);
//继续去找小串出现的位置索引
index = bigString.indexOf(minString);
System.out.println("找到了小串,截取后的大串为:"+bigString);
}
}
System.out.println("======================================================");
System.out.println(minString + "在大串" + bigString + "中出现的次数为:" + count);
}
}