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);
        }
    }
    
    

    结果

  • 相关阅读:
    电话聊天狂人
    PAT 1080. MOOC期终成绩
    PAT 1079. 延迟的回文数
    [转载]matlab 中序列求极值的方法
    [转载][转]Matlab-寻找峰值函数
    [转载]Kirchhoff Migration Impulse Response
    Envelope Extraction Using the Analytic Signal
    [转载]地震动的挑选
    C笔记
    Git常用有用命令
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8934211.html
Copyright © 2011-2022 走看看