zoukankan      html  css  js  c++  java
  • 替换空格 4

    先遍历每个字符统计空格数 String.charAt()

       

    根据空格数计算新的长度 newLength=oriLength+2*NumOfBlank

       

    新建一个newLength长度的字符数组tempChars用于存放替换空格之后的字符数组

       

    利用System.arraycopy函数将原字符串转换为数组拷贝到新的字符数组tempChars

       

    从新字符数组末尾开始遍历,用一个index1指向新字符数组末尾,用一个index2指向原字符数组末尾所在新字符数组的位置,将原字符数组逐个复制到新的字符数组的位置,遇到空格,替换,此时index1动,index2不动

       

    复杂度O(n),如果是从前往后复制的话复杂度O(n^2)

       

    package replaceBlank;

       

    public class ReplaceBlank {

    public static int getBlankNum(String testString) {

    int count = 0;

    for (int i = 0; i < testString.length(); i++) {

    String tempString = String.valueOf(testString.charAt(i));

    if (tempString.equals(" ")) {

    count++;

    }

    }

       

    return count;

    }

       

    public static void main(String[] args) {

    // TODO Auto-generated method stub

    String string = "we are here";

    replaceBlank(string);

    }

       

    static void replaceBlank(String string){

    if (string==null) {

    return;

    }

    int orgLength=string.length();

    int numOfBlank=0;

    for (int i = 0; i < string.length(); i++) {

    String tempString = String.valueOf(string.charAt(i));

    if (tempString.equals(" ")) {

    numOfBlank++;

    }

    }

    int newLength=orgLength+2*numOfBlank;

    char[] tempChars=new char[newLength];

    System.arraycopy(string.toCharArray(), 0, tempChars, 0, string.length());

    System.out.println("orgLength:"+orgLength+" "+"numOfBlank:"+numOfBlank);

    int indexOfOrgChars=orgLength-1;

    int indexOfNewChars=newLength-1;

    while (indexOfOrgChars>=0&&indexOfNewChars!=indexOfOrgChars) {

    if (tempChars[indexOfOrgChars]==' ') {

    tempChars[indexOfNewChars--]='%';

    tempChars[indexOfNewChars--]='2';

    tempChars[indexOfNewChars--]='0';

    }else {

    tempChars[indexOfNewChars--]=tempChars[indexOfOrgChars];

    }

    indexOfOrgChars--;

    }

    System.out.println(tempChars);

    }

    }

  • 相关阅读:
    帆软 控件内容 清除
    Spring MVC 拦截器
    jsp文件调用本地文件的方法(Tomcat server.xml 设置虚拟目录)
    Junit 4 测试中使用定时任务操作
    通过URL传递PDF名称参数显示PDF
    SpringMVC 无法访问到指定jsp页面可能的原因
    优化小技巧——复杂属性对象的read模式
    [as部落首发]网页游戏开发中的一些小技巧
    Flash Platform 游戏开发入门
    理解 Flash 中的 ActionScript 3 调试
  • 原文地址:https://www.cnblogs.com/keedor/p/4379086.html
Copyright © 2011-2022 走看看