当前位置:网站首页>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;
}如图所示为运行结果:

输出完成
如图,替换已完成。
边栏推荐
- mk file introduction
- Scene-driven feature calculation method OpenMLDB, efficient implementation of "calculate first use"
- The mount command - mounted read-only, solution
- Visual studio2019 配置使用pthread
- Day 79
- Day 84
- The Summer of Open Source 2022 is coming | Welcome to sign up for the OpenMLDB community project~
- JS小技巧,让你编码效率杠杠的,快乐摸鱼
- 本地服务配置内网穿透实现微信公众号整合
- Certificate of SearchGuard configuration
猜你喜欢
随机推荐
127.0.0.1 connection refused
JS案例练习(pink老师经典案例)
Certificate of SearchGuard configuration
Real-time Feature Computing Platform Architecture Methodology and Practice Based on OpenMLDB
精彩联动 | OpenMLDB Pulsar Connector原理和实操
helm安装
Byte (byte) and bit (bit)
厂商推送平台-华为接入
一文看懂注解与反射
PyQt5中调用.ui转换的.py文件代码解释
Scene-driven feature calculation method OpenMLDB, efficient implementation of "calculate first use"
将一个excel文件中多个sheet页“拆分“成多个“独立“excel文件
Day 87
Simple mine sweeping in C language (with source code)
解决AttributeError: ‘NoneType‘ object has no attribute ‘val‘ if left.val!=right.val:Line 17 问题
nepctf Nyan Cat 彩虹猫
The whole process of Tinker access --- Compilation
Jetpack之dataBinding
vim 编辑器使用学习
mongoose连接mongodb不错,显示encoding没有定义









