当前位置:网站首页>C language replaces spaces in strings with%20
C language replaces spaces in strings with%20
2022-07-02 08:28:00 【Ischanged】
subject : Please implement a function , Replace each space in the string with "%20". Examples : “abc defgx yz” turn “abc%20defgx%20yz”
First time to see this topic , I wrote the following error code , First of all, let's think about what's wrong ?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<assert.h>
char *replace(char *p)
{
assert(p != NULL);
char *s = p;
while (*p)
{
if (*p == ' ')
*p = "%20";
p++;
}
return s;
}
int main()
{
char a[] = "abc defgx yz";
replace(a);
printf("%s", a);// The result is :abc 躣躣躣躣躣躣躣躣躣躣躣 efgx 躽 z
return 0;
}
In fact, the simple idea of the above code is through pointers , Traverse this character array , If you find a space, replace it with %20, Always find the end of the string \0 Up to . But for this problem, I have neglected an important problem , Is that we find the space and replace it with %20, A space is a character ,%20 It's three characters , Replace three characters with one character , How can memory space be filled , Causes the array to be out of bounds , As for the result, it is also strange .
An array can't be troublesome , To find a space, you need to move the following element , Then we can define two arrays
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
void replace(char *arr1, char *arr2)
{
while (*arr1)
{
if (*arr1 != ' ')
{
*arr2 = *arr1;
arr2++;
}
else
{
strcpy(arr2, "%20");
arr2 = arr2 + 3;
}
arr1++;
}
*arr2 = '\0';
}
int main()
{
char arr1[] = "abc defgx yz";;// The array size is 13
char arr2[40];// Arbitrarily define the appropriate array size , I can put it down arr1 The content of
replace(arr1, arr2);
printf("%s", arr2);
return 0;
}
Program run results :
The basic implementation idea of the above code is :
- Define two arrays ,arr1 Used to store the original string ,arr2 Used to store added %20 String after
- Traverse the array through the pointer arr1, Look for spaces , Until you find the string \0 until , If it is not a space during traversal , Character by character arr1 Put the content of arr2 Inside , If you encounter a space, put it after the character that is not a space , hold %20 Copy to the end of the string ,arr2 The space in front is full , So the position of the next character should be moved back three positions . Continue to implement this Law .
- Finally, when you find arr1 Of \0 Replacement complete , stay arr2 After the replaced character, add \0 that will do ( because arr2 Only defined but not initialized , There's nothing in it )
Another algorithm is also ok , Look at the code first :
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<string.h>
char * replace (char *str)
{
char *p = str;
char arr[30];
while (*p != '\0')
{
if (*p == ' ')
{
strcpy(arr, p + 1);
*p = '%';
*(p + 1) = '2';
*(p + 2) = '0';
strcpy(p + 3, arr);
p = p + 3;// Three positions have been occupied ,p Move back three positions
continue;//p Already moved , So don't move , Use continue Skip the following code p++
}
p++;
}
return str;
}
int main()
{
char arr1[30] = "abc defgx yz";//14
//char arr2[40];
replace(arr1);
printf("%s", replace(arr1));
return 0;
}
This algorithm idea is a little similar to the above , The code above is added to the second array %20 after , Output this array arr2, Do not use the original array ; The following idea is to borrow an array to temporarily store things , I added %20 after , Then put the things temporarily stored behind the blank , Get back the original array .
The basic idea of the above code is : Every time you need to save the string after the space into an array , Then replace the space with %20 Then copy the string just copied to %20 You can just .
边栏推荐
- Use Matplotlib to draw a preliminary chart
- Global and Chinese market of wire loop, 2022-2028: Research Report on technology, participants, trends, market size and share
- Constant pointer and pointer constant
- c语言将字符串中的空格替换成%20
- DWORD ptr[]
- Carsim-路面3D形状文件参数介绍
- Learning C
- MySQL optimization
- What is SQL injection
- Web安全--核心防御机制
猜你喜欢

CarSim learning experience - rough translation 1

Array and string processing, common status codes, differences between PHP and JS (JS)

VS Code配置问题

Sqlyog remote connection to MySQL database under centos7 system

HCIA - application layer

CarSim problem failed to start solver: path_ ID_ OBJ(X) was set to Y; no corresponding value of XXXXX?

旋转链表(图解说明)

樂理基礎(簡述)

Static library and dynamic library

Carsim problem failed to start Solver: Path Id Obj (X) was set to y; Aucune valeur de correction de xxxxx?
随机推荐
Force deduction method summary: find classes
Valin cable: BI application promotes enterprise digital transformation
Longest isometric subsequence
OpenCV常用方法出处链接(持续更新)
Hcia - Application Layer
Learning C
Erase method in string
Sparse matrix storage
HCIA - data link layer
Comparison between setTimeout and requestanimationframe (page refresh)
Carsim-问题Failed to start Solver: PATH_ID_OBJ(X) was set to Y; no corresponding value of XXXXX?
CarSim learning experience - rough translation 1
Matlab other
sqli-labs第12关
Opencv3 6.3 reduced pixel sampling with filters
c语言自定义类型枚举,联合(枚举的巧妙使用,联合体大小的计算)
链表经典面试题(反转链表,中间节点,倒数第k个节点,合并分割链表,删除重复节点)
Global and Chinese markets for Salmonella typhi nucleic acid detection kits 2022-2028: Research Report on technology, participants, trends, market size and share
Jupyter Notebook常用快捷键(在命令模式中按H也可查看)
Network security - summary and thinking of easy-to-use fuzzy tester