第11次作业--字符串处理

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

 (1)

/*
 先声明一个int数组str,用来标记字符是否重复出现.
 使用了indexOf()和lastIntOf()函数,作用分别为返回某个字符或字符串首次出现的位置h和最后出现的位置t
 若h==t,则说明该字符只有一个
 若h!=t,说明不止一个,number++,将下标为[h~t)的字符串,递归,直至h==t,
 在此期间,每次都标记已经出现重复的t位置,令str[t] = 1
 */
package work;
import java.util.*;
public class work {
    public static class Lab3_2 {
        Scanner sc = new Scanner(System.in);
        static String s = new String("");
        static int fun1(String s2,char t,int str1[],int number)
        {    
                if(str1[s.indexOf(t)]!=0)
                {
                    
                    return 0;
                }
                if(s2.indexOf(t)==s2.lastIndexOf(t))
                {
                    
                    str1[s.indexOf(t)] = 1;
                    number++;
                    return number;
                     
                }
                else {
                    String s1 = s2.substring(s2.indexOf(t),s2.lastIndexOf(t));
                    str1[s.lastIndexOf(t)] = 1;
                    number++;
                    return fun1(s1,t,str1,number);
                }    
        }
        public static void main(String[] args) {
                Scanner sc = new Scanner(System.in);
                s = sc.nextLine();
                
                int str1[] = new int[100];
                for(int i =0;i<s.length();i++)
                {
                    
                    int k =fun1(s,s.charAt(i),str1,0);
                    if(k!=0)
                    {
                        System.out.println(s.charAt(i)+" "+k);
                    }
                    
                    
                }
            
                
        }
    }}

 (2)运行成功截图

 

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

(1)

package work;

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        String checkStr = null;
        System.out.print("请输入要检测的字符串:");
        Scanner in = new Scanner(System.in);
        checkStr = in.nextLine();
        if (isPaildrome(checkStr)) {
            System.out.print(checkStr + "是回文串。");
        } else {
            System.out.print(checkStr + "不是回文串。");
        }
    }

    private static boolean isPaildrome(String check) {
        // TODO Auto-generated method stub
        int low = 0;
        int high = check.length() - 1;
        while (low < high) {
            if (check.charAt(low) != check.charAt(high))
                return false;
            low++;
            high--;
        }

        return true;
    }
}

(2)成功运行截图

原文地址:https://www.cnblogs.com/912760869-qq/p/11890339.html