day08--String类的转换方法

This commit is contained in:
2025-12-30 13:59:50 +08:00
parent 9ce454c371
commit 0b27004642
2 changed files with 67 additions and 0 deletions

View File

@@ -4,9 +4,36 @@ String判断方法和获取方法的练习
定义一个方法动态的计算出第n个子字符串所在的索引如果没有第n个要显示出它一共有几个子字符串返回-1表示找不到如果 定义一个方法动态的计算出第n个子字符串所在的索引如果没有第n个要显示出它一共有几个子字符串返回-1表示找不到如果
有第n个就不用显示直接返回索引即可。 有第n个就不用显示直接返回索引即可。
123123123321abc
第3个"123"的索引 6
第4个"123"的索引 -1 当前只有3个123
*/ */
public class Demo05 { public class Demo05 {
public static void main(String[] args) { public static void main(String[] args) {
String str = "12a12b12c123";
int index = getIndex(str, "12", 2);
System.out.println(index);
} }
public static int getIndex(String str ,String subStr,int n){
//记录索引,为找下一个子字符串做准备
int index = 0;
//记录找到的次数
int count = 0;
for (int i = 0; i < n; i++) {
index = str.indexOf(subStr, index);
if (index != -1) {
count++;
index++;
} else {
System.out.println(""+str+"中,只有"+count+"个子字符串"+subStr);
return -1;
}
}
index--;
return index;
}
} }

View File

@@ -0,0 +1,40 @@
package com.inmind.string01;
/*
常用类_String的转换方法_replace_toCharArray_getBytes
public char[] toCharArray () :将此字符串转换为新的字符数组。
public byte[] getBytes () :使用平台的默认字符集将该 String编码转换为新的字节数组。
public String replace (CharSequence target, CharSequence replacement) 将与target匹配的字符串使
用replacement字符串替换。
*/
public class Demo06 {
public static void main(String[] args) {
//public String replace (CharSequence target, CharSequence replacement) 将与target匹配的字符串使用replacement字符串替换。
String str = "今天,天气很好,我很高兴";
//把字符串中的所有“天”替换为*
String newStr = str.replace("", "**");
System.out.println(str);
System.out.println(newStr);
}
private static void method2() {
//public byte[] getBytes () :使用平台的默认字符集将该 String编码转换为新的字节数组。
String str = "abc";//a:97
byte[] bytes = str.getBytes();
for (int i = 0; i < bytes.length; i++) {
System.out.println(bytes[i]);// 97 98 99
}
}
private static void method1() {
//public char[] toCharArray () :将此字符串转换为新的字符数组。
String str = "hello";
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
System.out.println(chars[i]);
}
System.out.println(chars);//chars保存的是地址直接打印字符数组由于println方法的源码导致打印字符数组中打印的内容
}
}