zoukankan      html  css  js  c++  java
  • JZ-C-04

    剑指offer第四题:字符串中替换空格

     1 //============================================================================
     2 // Name        : JZ-C-04.cpp
     3 // Author      : Laughing_Lz
     4 // Version     :
     5 // Copyright   : All Right Reserved
     6 // Description : Hello World in C++, Ansi-style
     7 //============================================================================
     8 
     9 #include <iostream>
    10 #include <string.h>
    11 #include <string>
    12 using namespace std;
    13 
    14 char* ReplaceBlank(char string[]) {
    15     int length = strlen(string);
    16     if (length > 0) {
    17         int number = 0; //初始化
    18         for (int i = 0; i < length; i++) {
    19             if (string[i] == ' ') {
    20                 number++; //先记录空格数
    21             }
    22         }
    23         int newLength = length + number * 2; //重新定义字符串长度
    24         char* result = new char[newLength]; //定义新的字符串
    25         char *p, *q; //定义两个指向两字符串的指针
    26         p = string;
    27         q = result;
    28         int pIndex = length - 1; //从字符串末尾向前依次输出,遇到空格,转换为%20
    29         int qIndex = newLength - 1;
    30         while (pIndex >= 0 && qIndex >= 0) {
    31             if (p[pIndex] == ' ') {
    32                 q[qIndex--] = '0';
    33                 q[qIndex--] = '2';
    34                 q[qIndex--] = '%';
    35                 pIndex--;
    36             } else {
    37                 q[qIndex--] = p[pIndex--];
    38             }
    39         }
    40         q[newLength] = '';//最后补位''
    41         return result;
    42     } else {
    43         cout << "字符串为空" << endl;
    44         return NULL;
    45     }
    46 }
    47 int main() {
    48     char string[] = "Hello World ";
    49     char* result = ReplaceBlank(string);
    50     cout << "转换后:" << result << endl;
    51     delete[] result;//释放内存,针对函数里的char* result =new char[...] ?
    52     return 0;
    53 }
    —————————————————————————————————————行走在人猿的并行线——Laughing_Lz
  • 相关阅读:
    /usr/bin/ld: 找不到 /usr/lib64/libatomic.so.1.0.0
    linux Version mismatch error. This is libtool 2.4.6 Debian-2.4.6-2
    java播放语音文件
    java冒泡排序
    java递归求和
    常见芯片标号说明
    keil5 新建 stm32项目 步骤
    st-link 升级固件时报错“is not in the DFU mode”
    数码管 段选位选
    C51 定时器
  • 原文地址:https://www.cnblogs.com/Laughing-Lz/p/5499593.html
Copyright © 2011-2022 走看看