java有关string字符串编程习题

1.一个字符串最后一个单词的长度(字符串单词之间为空格,结尾不为空格)

    //最后一个单词的长度
    //方法1
    public static void main1(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) { // 注意 while 处理多个 case
            String str = in.nextLine();
            int index = str.lastIndexOf(" ");
            int len = str.length()-index-1;
            System.out.println(len);
        }
    }
    //方法2
    public static void main2(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String str = in.nextLine();
            String[] strs = str.split(" ");
            String str1 = new String("");
            for(int i = 0;i<strs.length;i++){
                if(i==strs.length-1){
                    str1 += strs[i];
                }
            }
            System.out.println(str1.length());
        }
    

2.字符串中首个出现一次的字母

    //首个出现一次的字母
    public int firstUniqChar(String s) {
        int[] count = new int[256];
        // 统计每个字符出现的次数
        for(int i = 0; i < s.length(); ++i){
            count[s.charAt(i)]++;
        }
        // 找第一个只出现一次的字符
        for(int i = 0; i < s.length(); ++i){
            if(1 == count[s.charAt(i)]){
                return i;
            }
        }return -1;
    }

3.字符串是否为回文

    //回文检查
    public static boolean isValidChar(char ch){
        if((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')){
            return true;
        }
        return false;
    }
    public boolean isPalindrome(String s) {
        // 将大小写统一起来
        s = s.toLowerCase();
        int left = 0, right = s.length()-1;
        while(left < right){
            // 1. 从左侧找到一个有效的字符
            while(left < right && !isValidChar(s.charAt(left))){
                left++;
            }
            // 2. 从右侧找一个有效的字符
            while(left < right && !isValidChar(s.charAt(right))){
                right--;
            }
            if(s.charAt(left) != s.charAt(right)){
                return false;
            }else{
                left++;
                right--;
            }
        }
        return true;
    }

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值