当前位置:网站首页>C语言-6月12日-字符替换问题,将一个‘ ’替换为2个‘#’
C语言-6月12日-字符替换问题,将一个‘ ’替换为2个‘#’
2022-08-11 05:30:00 【曾铎000811】
执行替换规则的前后:"i am a student" -> "i##am##a##student"
首先要明确的问题是:在字符串已经给定的情况下,如何对字符串中的空格进行字符替换?
这个问题可以分为几部分,分步来进行分析最终逐步进行解决:
一:让计算机对已经存在的字符串进行扫描,并且识别出空格字符
二:识别出空格字符后,如何将‘##’与‘ ’进行替换
三:替换后让计算机直接进行输出
思路:我们可以直接创建一个大数组用来存放替换空格和“##”后的字符串,使用一个下标创建对原数组(原字符串)的循环体,从而进行对原数组的扫描,当下标扫描每一个字符时,只要下标所对应的字符不为空格,直接将字符传送进大数组中;使用j对大数组进行扫描,如果i下标对应的字符是空格的话,则直接将大数组中j下标对应的位置替换为‘##’,步骤执行结束之后直接对大数组进行输出。
分析完成,将思路代码化:
//字符替换问题,将字符串中的空格替换为## 1个‘ ’替换成两个‘##’
//str -> i am a student aim -> i##am##a##student
//思路:开辟一个数组,使用i下标对str数组进行扫描,使用j下标对aim数组进行扫描
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
char *Replace(char *str,char *aim,int strlen)//定义替换函数
{
assert(str != NULL && aim != NULL && strlen > 0);//断言式
int i = 0,j = 0;//定义两个下标,i下标对原str数组进行遍历,j对aim数组进行遍历
while(i < strlen){
if(str[i] != ' '){//当前位置不是空格的情况下
aim[j++] = str[i++];//先用变量的值,然后自增
/*
此处语句的意思是这几句子合并之后的句子:
aim[j] = str[j];
i++;
j++
*/
}
else{//当前位置为空格
aim[j++] = '#';
aim[j++] = '#';
i++;
/*
此处语句的意思是这几句子合并之后的句子:
aim[j] = '#';
j++;
aim[j] = '#';
j++;
i++;
*/
}
}
return aim;
}
int main()
{
char str[] = "i am a student";//定义字符数组
printf("替换前的字符串为:%s",str);
char aim[256] = {0};
int len = sizeof(str) / sizeof(str[0]);
Replace(str,aim,len);//调用替换函数
printf("\n替换后的字符串为:%s",aim);//直接对aim字符串进行输出
return 0;
}
如图所示为运行结果:
输出完成
如图,替换已完成。
边栏推荐
猜你喜欢
Visual studio2019 配置使用pthread
gerrit configure SSH Key and account, email information
heap2 (tcache attack,house of orange)
IndexError: index 9 is out of bounds for axis 0 with size 9;数组下标溢出问题
虚拟机更改IP地址
OpenMLDB: Consistent production-level feature computing platform online and offline
js learning advanced BOM part (pink teacher notes)
开发公众号授权遇到的redirect_uri参数错误
Scene-driven feature calculation method OpenMLDB, efficient implementation of "calculate first use"
The official website of OpenMLDB is upgraded, and the mysterious contributor map will take you to advance quickly
随机推荐
three.js基础学习
PyQt5中调用.ui转换的.py文件代码解释
连接数据库时出现WARN: Establishing SSL connection without server‘s identity verification is not recommended.
开源之夏 2022 火热来袭 | 欢迎报名 OpenMLDB 社区项目~
JS advanced web page special effects (pink teacher notes)
Wonderful linkage | OpenMLDB Pulsar Connector principle and practical operation
JVM tuning and finishing
C-动态内存管理
Tinker接入全流程---配置篇
微信小程序云开发项目wx-store代码详解
Building a data ecology for feature engineering - Embrace the open source ecology, OpenMLDB fully opens up the MLOps ecological tool chain
IO流和序列化与反序列化
Day 72
2021-09-11 C language variables and memory allocation
Fourth Paradigm OpenMLDB optimization innovation paper was accepted by VLDB, the top international database association
Pinyougou project combat notes
swagger错误:WARN i.s.m.p.AbstractSerializableParameter - [getExample,421] - Illegal DefaultValue null
Jetpack使用异常问题集锦
第一章 Verilog语言和Vivado初步使用
JS进阶网页特效(pink老师笔记)