对于JAVA中字符串小白的一些学习路径
欢迎大神指导
大家好,我是dreampossible007。第一次写博客,没想到我的第一次居然给了CSDN,不过我是自愿的,我是在校的一名大二学生,刚开始学习JAVA,现在在学习字符串的一些操作,我想记录下来,以便于后面的学习中可以随即拿出来用。大佬勿喷0.0
今天学习了十种字符串的操作,现在我将它写下来
- 获取字符串的长度 length();
- 字符串的查找 indexOf() 是字符串首次出现的位置;lastindexOf() 是字符串最后一次出现的位置
- 获取指定搜索位置的字符charAT();
- 获取子字符串 substring();
- 去除前部和尾部空格trim();
- 字符串的替换replace(),需要注意的是oldchar换的字母大小写一定要相同,否则不能实现
- 判断字符串的开头和结尾 startsWith() 是判断开头的;endsWith() 是判断结尾的
- 判断字符串是否相等equals()[是不能忽视大小写的];equalsIgnoreCase()[是可以忽视大小写]
- 按照字典顺序比较两个字符串 compareTo() 假如比较x,y,若x在y的前面,输出负数;反之输出整数,具体的数字要看两个字符串的距离。
- 字母大小写转换;toLowerCase() 是大写->小写的转换;toUpperCase() 是小写->大写的转换。
代码的具体实现操作
import java.util.Scanner;
public class praticeString {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
String a=" I LOVE YOU! ";
int length=a.length();//获取字符串长度
int indexOf=a.indexOf(‘L’);//字符串首次出现的位置
char charAT=a.charAt(6);//获取指定搜索位置的字符
String substr=a.substring(2);//获取子字符串
String newa=a.trim();//去除字符串的空格
String newstr=a.replace(‘U’, ‘s’);//替换字符串;
boolean b=a.startsWith(“i”);//判断开头是否是i 记住是双引号;
boolean c=a.endsWith(“U!”);//判断结尾是不是U
boolean d=a.equals(“i love you”);//判断字符串是否相等 equals是区分大小写的
boolean e=a.equalsIgnoreCase(“i love you!”);//判断字符串是否相等 equalsIgonrecase是不区分大小写的
String a2=new String(“a”);//对字符进行比较,要是前者位于后者前面,则输出负数;反之输出正数;具体数字根据之间的差距
int f=a2.compareTo(“c”);
String a3=a.toLowerCase();//对字符串大小写进行转化 toLowerCase()是大->小;toUpperCase()是小->大;
System.out.println(a);
System.out.println(length);
System.out.println(indexOf);
System.out.println(charAT);
System.out.println(substr);
System.out.println(newa);
System.out.println(newstr);
System.out.println(b);
System.out.println©;
System.out.println(d);
System.out.println(e);
System.out.println(a2);
System.out.println(f);
System.out.println(a3);
}
漂亮的代码片
下面展示同样高亮的 代码片
import java.util.Scanner;
public class praticeString {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
String a=" I LOVE YOU! ";
int length=a.length();//获取字符串长度
int indexOf=a.indexOf('L');//字符串首次出现的位置
char charAT=a.charAt(6);//获取指定搜索位置的字符
String substr=a.substring(2);//获取子字符串
String newa=a.trim();//去除字符串的空格
String newstr=a.replace('U', 's');//替换字符串;
boolean b=a.startsWith("i");//判断开头是否是i 记住是双引号;
boolean c=a.endsWith("U!");//判断结尾是不是U
boolean d=a.equals("i love you");//判断字符串是否相等 equals是区分大小写的
boolean e=a.equalsIgnoreCase("i love you!");//判断字符串是否相等 equalsIgonrecase是不区分大小写的
String a2=new String("a");//对字符进行比较,要是前者位于后者前面,则输出负数;反之输出正数;具体数字根据之间的差距
int f=a2.compareTo("c");
String a3=a.toLowerCase();//对字符串大小写进行转化 toLowerCase()是大->小;toUpperCase()是小->大;
System.out.println(a);
System.out.println(length);
System.out.println(indexOf);
System.out.println(charAT);
System.out.println(substr);
System.out.println(newa);
System.out.println(newstr);
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(e);
System.out.println(a2);
System.out.println(f);
System.out.println(a3);
}