100天代码提升计划-第5天
String(三)
1.string种与转换相关的方法
public char【 】tocharArray()将当前字符串转换成字符数组
public byte【 】getBytes()获得当前字符串的底层字节数组
public string replacr(charSequence oldString,charSequence newString) 将老字符串替换成新的字符串,返回新字符串
package com.course.demo; public class Demo001 { public static void main(String[] args) { //转换成字符数组 char[] str = "hello".toCharArray(); System.out.println(str[3]);//l System.out.println(str.length);//5 //转换成字符数组 byte[] bytes = "abc".getBytes(); for (int i = 0; i < bytes.length; i++) { System.out.println(bytes[i]);//97 98 99 } //字符串的内容替换 String str1="how are you?"; String str2 = str1.replace("o", "a"); System.out.println(str1); //how are you? System.out.println(str2);//haw are yau? } }
2.字符串的分割方法
public string【】 split(String regex)按照参数规则,将字符串切换成若干部分
注: split方法的参数其实是一个“正则表达式”,如果按钮“.”(英文点)进行且分时必须写“\\.”
package com.course.demo; public class Demo001 { public static void main(String[] args) { String str1="aaa,bbb,ccc"; String[] str2= str1.split(","); for (int i = 0; i < str2.length; i++) { System.out.println(str2[i]); } System.out.println("=========="); String str3="how are you "; String[] str4 = str3.split(" "); for (int i = 0; i < str4.length; i++) { System.out.println(str4[i]); } String str5="aaa.ccc.vvv.ddd"; String[] split = str5.split("\\."); for (int i = 0; i < split.length; i++) { System.out.println(split[i]); } } }
练习:定义一个方法,把数组【1,2,3】按照指定格式拼接一个字符串,输入的格式为【word1#word2#word3】
package com.course.demo; public class Demo001Lianxi { public static void main(String[] args) { int [] a={1,2,3,4,5,6}; String jg=fangfa(a); System.out.println(jg); } public static String fangfa( int[] a){ String s="["; for (int i = 0; i < a.length; i++) { if (i==a.length-1){ s+="word"+a[i]+"]"; }else { s+="word"+a[i]+"#"; } } return s; } }
练习2:键盘输入一个字符串,判断各个字符出现的次数
字符种类:大写字母,小写字母,数字,其他
package com.course.demo; import java.util.Scanner; public class Demo001Lianxi { public static void main(String[] args) { Scanner sc =new Scanner(System.in); System.out.println("请输入一串字符"); String zf=sc.next(); int dz=0; int xz=0; int sz=0; int qt=0; char[] chars = zf.toCharArray(); for (int i = 0; i < chars.length; i++) { char dg =chars[i]; if ('A'<=dg && dg<='Z'){ dz++; }else if ('a'<=dg && dg<='z'){ xz++; }else if ('0'<=dg && dg<='9'){ sz++; }else { qt++; } } System.out.println("大写字母有"+dz); System.out.println("小写字母有"+xz); System.out.println("数字有"+sz); System.out.println("其他字符有"+qt); } }

浙公网安备 33010602011771号