字符串处理

题目一:

编写一个应用程序,统计输入的一个字符串中相同字符的个数,并将统计结果输出。

代码:

1.Test.java

 1 package cn.edu.ccut;
 2 import java.util.*;
 3 
 4 public class Test {
 5 
 6     public static void main(String[] args) {
 7         System.out.println("请输入字符串");
 8         Scanner sc = new Scanner(System.in);
 9         String str1 = sc.nextLine();     // 从键盘接受字符串输入;
10         for(int i = 0 ; i < str1.length() ; i++){
11             char c = str1.charAt(i);        // 拆分单个字符;
12             String str2= new Character(c).toString(); // char类型装换成String;
13             if(str1.indexOf(c) == i){     //判断该字符是否第一次出现;
14                 int count = 0;
15                 for(int j = 0 ;  j < str1.length() ; j++){
16                     if(str1.regionMatches(j, str2, 0, 1)){ //查找相同字母;
17                         count++;
18                     }                    
19                 }
20                 System.out.println(""+c+"出现了"+count+"次");
21             }        
22         }
23     }
24 }

运行结果:

 

 题目二:

编写程序,输入一个字符串,判断该串中的字母能否组成一个回文串(回文串:一个字符串从前向后读取和从后向前读取都一样)。如:ab<c>c?ba

 代码:

1、Test.java

 1 package cn.edu.ccut.project2;
 2 
 3 import java.util.Scanner;
 4 
 5 public class Test {
 6 
 7     public static void main(String[] args) {
 8         System.out.println("请输入字符串");
 9         Scanner sc = new Scanner(System.in);
10         String str1 = sc.nextLine();     // 从键盘接受字符串输入;
11         String str2 = str1.replaceAll("[\\P{Punct}\\P{Space}]+",""); //正则表达式剔除特殊符号
12         StringBuffer str = new StringBuffer(str2); 
13         if(str2.equals(str.reverse().toString())){ //领用StringBuffer类倒置与原串比较
14             System.out.println("是回文串");
15         }
16         else{
17             System.out.println("不是回文串");
18         }
19     }
20 }

运行结果:

 

 

posted @ 2019-11-19 21:13  chris丶w  阅读(205)  评论(0编辑  收藏  举报