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

    }

    }

  • 相关阅读:
    古文_硕鼠,原文及翻译
    使用php模拟post的几种方法
    alpha版、beta版、rc版的意思
    8007003Windows Update遇到未知错误
    树上10只鸟,开枪打死1只,还剩几只?
    [转]乐死我了,怎么样成为一个全栈程序员(Full Stack Developer),附我想专注的语言
    [转]Visual C++ RunTime的特征——非烫即屯
    斗破苍穹中的几个人物图片
    吐槽一下中国的大学的教材
    百度知道里关于C++的讨论
  • 原文地址:https://www.cnblogs.com/keedor/p/4379086.html
Copyright © 2011-2022 走看看