zoukankan      html  css  js  c++  java
  • 《程序员代码面试指南》第五章 字符串问题 字符串的调整与替换

    题目

    字符串的调整与替换
    

    java代码

    package com.lizhouwei.chapter5;
    
    /**
     * @Description: 字符串的调整与替换
     * @Author: lizhouwei
     * @CreateDate: 2018/4/24 22:13
     * @Modify by:
     * @ModifyDate:
     */
    public class Chapter5_10 {
    
        public String repalce(char[] chars) {
            int len = 0;
            int num = 0;
            for (len = 0; len < chars.length && chars[len] != 0; len++) {
                if (chars[len] == ' ') {
                    num++;
                }
            }
            int j = len + 2 * num - 1;
            for (int i = len - 1; i > -1; i--) {
                if (chars[i] != ' ') {
                    chars[j--] = chars[i];
                } else {
                    chars[j--] = '0';
                    chars[j--] = '2';
                    chars[j--] = '%';
                }
            }
            return String.valueOf(chars);
        }
    
        public String modify(char[] chars) {
            int j = chars.length - 1;
            for (int i = chars.length - 1; i > -1; i--) {
                if (chars[i] != '*') {
                    chars[j--] = chars[i];
                }
            }
            for (; j > -1; j--) {
                chars[j] = '*';
            }
            return String.valueOf(chars);
        }
    
        //测试
        public static void main(String[] args) {
            Chapter5_10 chapter = new Chapter5_10();
            char[] str = new char[100];
            str[0] = 'a';
            str[1] = ' ';
            str[2] = 'b';
            str[3] = ' ';
            str[4] = ' ';
            str[5] = 'c';
            String result = chapter.repalce(str);
            System.out.println("字符串 a b  c 替换空格后为:" + result);
            char[] str2 = {'*', '1', '2', '*', '3', '*'};
            String result2 = chapter.modify(str2);
            System.out.println("字符串{'*','1','2','*','3','*'}调整后为:" + result2);
        }
    }
    
    

    结果

  • 相关阅读:
    Windows徽标键(WinKey)的屏蔽和恢复
    合肥轨道交通线路图(2025+ / 运营版)
    cmake未找到命令解决
    python3 用requests.get获取网页内容为空 <Response [200]>
    磁盘问题修复
    双机热备vrrp
    华为 nat策略
    策略实验2
    防火墙安全策略
    华为防火墙策略配置(http、icmp包允许通过)
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8934211.html
Copyright © 2011-2022 走看看