String 索引 ,常见比较和替换方法
charAt 的使用
提取字符串指定未知字符 (下标从 0 开始 ) 下标不可越界
public char charAt(char index){
return char;
}
*****************************************
class TestStringEquals{
public static void main(String[] args){
String s1 = "hello";
String s2 = "hello";
char s4 = s1.charAt(0);
System.out.println(s4);
}
}
求字符串的长度
public int length(){
return length;
}
**********************************************
class TestStringEquals{
public static void main(String[] args){
String s1 = "hello";
String s2 = "hello";
char s4 = s1.charAt(0);
System.out.println(s2.length());
}
}
查找字符串
查找字符串第一次出现位置
public int indexOf(String str){
return indexOf;
}
//查找第一次出现位置
class TestStringEquals{
public static void main(String[] args){
String s1 = "hello";
String s2 = "hello";
char s4 = s1.charAt(0);
System.out.println(s2.length());
int num = s1.indexOf("l");
System.out.println(num);
}
}
//查找 字符串 出现次数
class TestStringEquals{
public static void main(String[] args){
String s1 = "hello";
String s2 = "hello";
char s4 = s1.charAt(0);
System.out.println(s2.length());
indexOf(s1);
}
public static void indexOf(String str){
int count = 0;
String a = "o";
while(true){
if(str.contains(a)){
count ++;
str= str.replaceFirst(a, " ");//需要让 str重新接受 定义以后的 str新数组
}else{
break;
}
}
System.out.println(count);
}
//方法二
// public static int indexOf(String str){
//int count = 0;
// String a = "l";
//for(int i= 0 ; i <str.length(); i++){
//if(str.contains(a)){
// count++;
// str= str.replaceFirst(a, " ");
/ }
// }
// return count;
// }
}
指定字符串查找
第一次出现 索引位置,从指定索引的fromlndex处开始搜索
class TestStringEquals{
public static void main(String[] args){
String s1 = "hello";
String s2 = "hello";
char s4 = s1.charAt(0);
int num2 = s1.indexOf("o",3);
System.out.println(num2);
}
}
字符串比较
将String字符串与其他字符串比较大小(不区分大小写)
lass TestStringEquals{
public static void main(String[] args){
String s1 = "hello";
String s2 = "Hello";
char s4 = s1.charAt(0);
System.out.println( s1.equalsIgnoreCase(s2));
// int num2 = s1.indexOf("o",3);
// System.out.println(num2);
}
}
替换字符串
(替换的字符串 是指定的所有字符串),字符串 不可变 需要去接新的 字符串
class TestStringEquals{
public static void main(String[] args){
String s1 = "hello";
String s2 = "Hello";
char s4 = s1.charAt(0);
System.out.println( s1.equalsIgnoreCase(s2));
s1 = s1.replace("l", "n");
System.out.println(s1);
// int num2 = s1.indexOf("o",3);
// System.out.println(num2);
}
}
综合练习:
class TestArrayMethod{
public static void main(String[] args) {
String s1 = "Blue brigd";
String s2 ="Blue Brigd";
//查找字符一第一个字母
System.out.println(s1.charAt(3));
//查询 字符s1 的长度
System.out.println(s1.length());
//查找字符串的位置
System.out.println(s1.indexOf("brigd"));
//比较s1 与s2 是否相等
System.out.println( s1.equals(s2));//不区分大小写
System.out.println(s1.equalsIgnoreCase(s2));//区分大小写
//字符串替换
String s = "我是小学生";
s= s.replaceAll("我", "你");
System.out.println(s);
}
}