day08--String类的转换方法
This commit is contained in:
@@ -4,9 +4,36 @@ String判断方法和获取方法的练习
|
||||
|
||||
定义一个方法,动态的计算出第n个子字符串所在的索引,如果没有第n个,要显示出它一共有几个子字符串,返回-1表示找不到,如果
|
||||
有第n个就不用显示,直接返回索引即可。
|
||||
123123123321abc
|
||||
第3个"123"的索引 6
|
||||
第4个"123"的索引 -1 当前只有3个123
|
||||
|
||||
*/
|
||||
public class Demo05 {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
40
day08/src/com/inmind/string01/Demo06.java
Normal file
40
day08/src/com/inmind/string01/Demo06.java
Normal 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方法的源码,导致打印字符数组中打印的内容
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user