【C语言】”student a am i “和“we are happy”
来源:互联网 发布:发型设计软件免费版 编辑:程序博客网 时间:2024/05/29 11:47
1.有一个字符数组的内容为 : “student a am i”, 请你将数组的内容改为”i am a student”.
要求:不能使用库函数。只能开辟有限个空间(空间个数和字符串的长度无关)。
思路:student a am i ->i ma a tneduts ->i am a student
也就是说先将所有的字符进行逆置,然后对每一个单词进行逆置。
#include<stdio.h>#include<assert.h>int my_len(char *str){ assert(str); int count = 0; while (*str++) { count++; } return count;}void reverse(char *start, char *end){ assert(start&&end); while (start < end) { char tmp = *start; *start = *end; *end = tmp; start++; end--; }}void str_reverse(char *str){ assert(str); int len = my_len(str); reverse(str, str + len - 1); //全部逆置 while (*str != '\0') { char *pos = str; while((*str != ' ')&&(*str!='\0')) { str++; } reverse(pos, str - 1); //每个单词的逆置 if (*str != '\0') str++; }}int main(){ char str[] = "student a am i"; str_reverse(str); printf("%s\n", str); system("pause"); return 0;}
2.字符串替换空格
请实现一个函数,把字符数组中的每个空格替换成“%20”。
例如输入“we are happy.”,则输出“we%20are%20happy.”。
思路:先统计出字符串中有多少个空格,因为加“%20”后,整体的长度增加了“原长度+空格*2”个,然后把最后一个向后移动,遇到空格的时候,依次替换为”%20”。
#include<stdio.h>#include<string.h>void replace_space(char *string,int len){ int count = 0; int i = 0; int pos = 0; int end = 0; int new_len = 0; for (i = 0; i < len; i++) { if (string[i] == ' ') count++; } new_len = len + 2 * count; pos = new_len - 1; end = len - 1; while (pos>end) { if (string[end] == ' ') { string[pos--] = '0'; string[pos--] = '2'; string[pos--] = '%'; } else { string[pos--] =string[end]; } end--; }}int main(){ char string[30] = "we are happy"; int len = strlen(string); replace_space(string, len); printf("%s\n", string); system("pause");}
其实大家可以看见,这两个题是比较相似的。不论是逆置还是添加,首先我们需要明白的是这个程序执行的过程,只有当整个流程都理顺了,才能很好的完成整个代码的书写。
0 0
- 【C语言】”student a am i “和“we are happy”
- 数组篇(1):给we are happy的每一个空格加“ ”、字符串逆序:i am a student
- 【c语言】把student a am i 变成 i am a student
- 【C语言】将字符串顺序翻转,如: I am a student 转成:student a am I
- 【C语言】将student a am i翻转成i am a student。
- C 语言字符串 将一行字符串I am a student。逆序输出student。a am I;
- C语言:如何将字符串“student a am I”转换为“I am a student”
- 【C语言】:字符串替换空格,输入“we are happy!”,输出”we%20are%20happy!“
- C 反转字符串中的单词 "student a am i " --> "i am a student "
- 【C】将字符数组的内容:"student a am i"改为"i am a student".
- 【C语言】有一个字符数组的内容为:"student a am i",请你将数组的内容改为"i am a student".
- 【C语言】有一个字符数组的内容为:"student a am i",请你将数组的内容改为"i am a student"
- 【面试常考】C语言:输入:"student a am i",输出"i am a student,不能使用库函数
- “I am a student”反转成“student a am I”
- I am a student. student.a am I
- student a am i -> i am a student
- 从"student a am i"到"i am a student"
- i am a student.转为student. a am i
- tomcat在eclipse中启动成功,主页却打不开
- 工作总结
- Windows内存清理工具实现——从现象到本质
- 2016年淘宝购买华硕FL5900UQ7500惨痛经历教训总结
- 牛客网刷题之复杂链表的复制
- 【C语言】”student a am i “和“we are happy”
- ksh getopts function
- 线性代数阶段性总结
- android 跑马灯效果的相关补充
- Zynq动态更新FPGA比特流
- ksh control statement
- 快速排序(C语言)
- ksh array variable
- 问题积累一