使用占位符构造动态字符串

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Stynis/article/details/80534319

实现功能:
       模拟采用占位符构造动态字符串的格式化方法。构造一句话,其中包含不定数量的用{}括起来的数字,如{0},{1},{2},并提示用户输入字符串,并按照顺序替换包括花括号在内的数字,从而构造出新的一句话,并打印输出。
运行程序示例:

The {0} of the {1} is {2}.
subject”,  ”course”, ”data structure

则输出 :

The subject of the course if data structure.

设计思路:
       根据要求,拟采用三个数组来进行存储。一个一维字符串数组tr1用于存储原本句子,一维整型数组num用于存储与括号内的数字,二维字符串数组tr2用于存储用来替换的内容,其中第一个下标对应将要替换的括号内的数字,数组内容为相应的替换内容(字符串)。
       在未扫描到“{”时则可以对tr1进行扫描打印,若查询到“{”,查询到之后读取括号后的数字,根据数字打印出tr2数组对应的内容,并将扫描位置向后跳3位(跳过数字和“}”),如此则可以打印出新的句子,实现要求。
       为防止同样的括号被重复计数,又设置了一个函数judge,在数值与已有数据不重复时返回1,否则返回0,由此可以控制num数组的读入,使得出现多次的同一种括号能被同样的内容替换。
       使用C++实现代码如下:

chuan.h

#include<string.h>
void putsnewstr(char tr1[], char tr2[][30]);
int judge(int num[],int n, int j);

chuan.cpp

#include<string.h>
#include"chuan.h"
void putsnewstr(char tr1[], char tr2[][30]) {
    int i = 0;
    while (tr1[i] != '\0') {
        if (tr1[i] != '{') { putchar(tr1[i]); i++; }
        else {
            int p = 0;
            while (tr2[tr1[i + 1] - '0'][p] != '\0') {
                putchar(tr2[tr1[i + 1] - '0'][p]);
                p++;
            }
            i += 3;
        }
    }printf("\n");
}

int judge(int num[],int n, int j) {
    while (n >= 0) {
        if (num[n] == j)return 0;
        else n--;
    }return 1;
}

main.cpp

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include"chuan.h"
int main() {
    char tr1[80];
    int num[10];
    char tr2[10][30];

    int i = 0, j = 0, n = 0;
    printf("inptut your sentence\n");
    gets(tr1);
    while (tr1[i] != '\0') {
        if (tr1[i] == '{') {
            if (judge(num, n,tr1[i + 1]-'0')) { 
                num[n] = tr1[i + 1]-'0';
                printf("to replace the{%d}is:\n", num[n]);
                j = 0;
                while ((tr2[num[n]][j] =getchar())!='\n') {
                    j++;
                }
                tr2[num[n]][j] = '\0';
                n++;
            }
        }
        i++;
    }
    putsnewstr(tr1, tr2);   
    system("pause");
}

程序运行结果如图:


chuan1.1

猜你喜欢

转载自blog.csdn.net/Stynis/article/details/80534319