1,length(); 返回字符串长度
2,split(); 字符串分割
3,indexOf 字符查询和字符串查询
4,equals() 字符串比较相同返回true不同返回false
5,compareTo() 字符串按照字典序比较大小,大于返回整数小于返回负数等于返回0
6,startsWith() 判断是否以某一个前缀开头
7,endsWith() 判断是否以某一个后缀开头
8,trim() 去掉首尾的空白字符和回车
9,toLowerCase() 字符串全部小写输出
10,toUpperCase 字符串全部大写输出
11,replace('A','a') 把字符串中的某一个字符全部转换为另一个字符(字符串也可以)
12,substring(1,4) 输出子串,两个整数为开始下标和结束下标,结束下标取不到
13,toCharArray() 将字符串转换成字符数组
字符串基础操作
java
import java.util.Scanner;
public class Main{
public static void main(String[] args){
//初始化
String a = "hello world";
String b = a; //存储到相同的地址
String c = a + b;
String s = "my age is " + 18; //字符串可以通过加号进行拼接,并且自动把非字符串的一部分变成字符串
String str = String.format("my ags is %d",18); //初始化字符串
String money_str = "123.12";
double money = Double.parseDouble(money_str); //把字符串转换成double类型
//访问字符串
for(int i=0;i<str.length();i++){
System.out.print(str.charAt(i));
}
}
}
代码实现
java
import java.util.Scanner;
import java.util.Arrays;
public class Main{
public static void main(String[] args){
String s = "hello world 2023";
String ss = "Hello world 2023";
System.out.println(s.length()); //返回字符串长度
String[] str = s.split(" "); //字符串分割变成字符串数组输出 双引号内为分割位置
System.out.println(Arrays.toString(str));
System.out.println(s.indexOf("l")); //返回字母第一次出现的下标,如果查找的不纯在就输出-1
System.out.println(s.indexOf("or")); //返回字符串第一次出现的第一个字母的下标
System.out.println(s.equals("hello world 2023")); //判断是否相同
System.out.println(s.equals(ss));
System.out.println(ss.compareTo("Aello world 2023")); //大于返回正值
System.out.println(ss.compareTo("hello world 2023")); //小于返回负值
System.out.println(ss.compareTo("Hello world 2023")); //等于返回0
System.out.println(s.startsWith("hello w")); //判断是否以某一个前缀开头
System.out.println(s.startsWith("helll"));
System.out.println(s.endsWith("2023")); //判断是否以某一个后缀开头
System.out.println(s.endsWith("2022"));
String mid = " AA2023bb ";
System.out.println(mid.trim()); //去掉首尾的空白字符和回车
System.out.println(mid.toLowerCase()); //字符串全部小写输出
System.out.println(mid.toUpperCase()); //字符串全部大写输出
System.out.println(mid.replace('A','a')); //把字符串中的某一个字符全部转换为另一个字符
System.out.println(mid.replace("bb","ccc")); //把字符串中的某一部分字符串全部转换为另一部分字符串
System.out.println(mid.substring(1,4)); //输出子串,两个整数为开始下标和结束下标,结束下标取不到
char[] cs = mid.toCharArray(); //将字符串转换成字符数组
System.out.println(Arrays.toString(cs));
for(char c:cs) //转换成字符数组后更加容易遍历
System.out.print(c);
}
}