当前位置:网站首页>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 .
边栏推荐
- Global and Chinese market of wire loop, 2022-2028: Research Report on technology, participants, trends, market size and share
- Static library and dynamic library
- File upload and download performance test based on the locust framework
- Summary of one question per day: String article (continuously updated)
- web安全--逻辑越权
- Intelligent manufacturing solutions digital twin smart factory
- 文件上传-upload-labs
- C language implements XML generation and parsing library (XML extension)
- Routing foundation - dynamic routing
- 力扣方法总结:查找类
猜你喜欢
Carsim-问题Failed to start Solver: PATH_ID_OBJ(X) was set to Y; no corresponding value of XXXXX?
DWORD ptr[]
CarSim learning experience - rough translation 1
[dynamic planning] p4170: coloring (interval DP)
St-link connection error invalid ROM table of STM32 difficult and miscellaneous diseases
c语言自定义类型枚举,联合(枚举的巧妙使用,联合体大小的计算)
Implementation of bidirectional linked list (simple difference, connection and implementation between bidirectional linked list and unidirectional linked list)
How to build the alliance chain? How much is the development of the alliance chain
Linked list classic interview questions (reverse the linked list, middle node, penultimate node, merge and split the linked list, and delete duplicate nodes)
Simple implementation scheme of transcoding and streaming (I)
随机推荐
Don't know mock test yet? An article to familiarize you with mock
Force deduction method summary: double pointer
SQL操作数据库语法
ICMP协议
高中数学必修一
STM32疑难杂症之ST-LINK Connection error INVALID ROM TABLE
Carsim 学习心得-粗略翻译1
Realize bidirectional linked list (with puppet node)
Comparison between setTimeout and requestanimationframe (page refresh)
My VIM profile
Li Kou daily one question brushing summary: binary tree chapter (continuous update)
Using C language to realize MySQL true paging
c语言将字符串中的空格替换成%20
Library function of C language
使用Matplotlib绘制图表初步
Intelligent manufacturing solutions digital twin smart factory
Global and Chinese market of electric cheese grinder 2022-2028: Research Report on technology, participants, trends, market size and share
Animation synchronization of CarSim real-time simulation
Array and string processing, common status codes, differences between PHP and JS (JS)
Matlab - autres