您的位置:首页 > 编程语言 > Java开发

JAVA中String类的练习

2018-09-18 21:31 633 查看
/*
* 需求:对字符串中的数据进行排序
* 1,将字符串转换成数组
* 2,对数组进行遍历排序
* 3,将数组转换为字符串
*/
public class Demo05 {
public static void main(String [] args) {
String s = "18995131310";
byte [] s1 = s.getBytes();//将字符串转换为字节数组
for(int i =0;i<s1.length-1;i++) {
for(int j=i+1;j<s1.length;j++) {
if(s1[i]>s1[j]) {
byte temp = s1[i];
s1[i] = s1[j];
s1[j] = temp;
}
}
}
String s2 = new String(s1);
System.out.println(s2);
}
}

/*
* 统计指定字符在字符串中的出现次数
* 1.需要取出每个字符(charAt),与指定的字符进行比较
* 2.遍历字符串,逐个比较。
* 3.设置计数器记录次数。
*/
public class Demo06 {
public static void main(String[] args) {
String s ="abcdfra";
char s1 = 'a';
int count = 0;
for(int i = 0;i<s.length();i++) {
char c = s.charAt(i);
if(c==s1) {
count++;
}
}
System.out.println(count);
}
}

/*
* 需求:对字符串按照指定的内容切割,然后排序;
* 1.运用split进行切割。
* 2.遍历数组排序。
*/
public class Demo07 {
public static void main(String[] args) {
String s = "asvv errg rewf gghj";
String [] s1 =s.split(" ");
for(int i =0;i<s1.length-1;i++) {
for(int j=i+1;j<s1.length;j++) {
if(s1[i].compareTo(s1[j])>0) {
String temp =s1[i];
s1[i] = s1[j];
s1[j] = temp;
}
}
}
String s2 = " ";
for(int i = 0 ; i<s1.length;i++) {
s2 = s2+s1[i]+" ";
}
System.out.println(s2);
}
}

/*
* 需求:把一个字符按照长度递减截取
*/
public class Demo08 {
public static void main(String[] args) {
String s = "abcde";
for(int i = 0;i<s.length();i++) {
for(int j=0,k=s.length()-i;k<=s.length();j++,k++) {
String sub = s.substring(j, k);
System.out.print(sub+"\t");
}
System.out.println(" ");
}
}
}

/*
* 模拟trim方法,去除字符串中的空格。
* 从两端开始寻找,用charAt获取字符,然后进行比较,
* 再用substring(int a,int b);进行截取!!
*/
public class Demo09 {
public static void main(String[] args) {
String s = "  abc def  ";
int start = 0;
int end =s.length()-1;
while(s.charAt(start)==' ') {
start++;
}
while(s.charAt(end)==' ') {
end--;
}
String s1 =s.substring(start, end+1);
System.out.println(s1);
}
}

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: