zoukankan      html  css  js  c++  java
  • 字符串一:替换空格()

    /**
     * 题目:替换空格()
     * 描述:请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
     * 解决方案: 方法一:   在java中,String有一个方法replaceAll(); 传入regex(匹配的正则)和replacecomment(要替换的字符)。
     *         方法二:   利用StringBuffer,遍历输入的字符串,是空格就往stringBuffer添加“%20”,不是空格就添加原来的字符。 利用indexof()和subSequence()
     *         方法三:   思路:
     *     步骤:①遍历原来的str,有空格就在原来的基础上添加两个空格
     *      ②定义两个指针 ,oldIndex是原来字符串的,newIndex是新的字符串的指针,都从最后一个元素开始
     *      ③进行遍历新的字符串,判断原来的字符串内容是否是空格。
     * */

    public class One {
    
        public static StringBuffer replaceSpace(StringBuffer str) {
            int length = str.length();
            for(int i=0;i<length;i++) {         //①遍历原来的str,有空格就在原来的基础上添加两个空格
                if(str.charAt(i) == ' ') {
                    str.append("  ");
                }
            }
            int oldIndex = length-1;
            int newIndex = str.length() -1;        //②定义两个指针 ,oldIndex是原来字符串的,newIndex是新的字符串的指针,都从最后一个元素开始
            while( newIndex >oldIndex  && newIndex > 0) {    
                if(str.charAt(oldIndex) == ' ') {        //③进行遍历新的字符串,判断原来的字符串内容是否是空格。
                    str.setCharAt(newIndex--,'0');
                    str.setCharAt(newIndex--,'2');
                    str.setCharAt(newIndex--,'%');
                }else {
                    str.setCharAt(newIndex--, str.charAt(oldIndex));
                }
                oldIndex--;
            }
            return str;
        }
        
        public static void main(String[] args) {
            StringBuffer input = new StringBuffer();
            input.append("we are faimly");
            System.out.println(replaceSpace(input));
        }
    }
    天助自助者
  • 相关阅读:
    利用python数据分析与挖掘相关资料总结
    pandas库学习笔记(一)Series入门学习
    mysql error:You can't specify target table for update in FROM clause
    查询及删除重复记录的SQL语句
    PHP tripos()函数使用需要注意的问题
    如何用git上传代码到github详细步骤
    这是我的第一篇博客
    html link js
    BOM与DOM
    创建简单的表单
  • 原文地址:https://www.cnblogs.com/ZeGod/p/9969374.html
Copyright © 2011-2022 走看看