标签:
6。1编写一个函数,它在一个字符串中进行搜索,查找所有在一个给定字符集中出现的字符,返回第一个找到的字符位置指针,未找到返回NULL
#include <stdio.h> char * find_char(char const *source, char const *chars) { char const *sptr = source; char const *cptr = chars; if (sptr == NULL || cptr == NULL) { return NULL; } while (*sptr != ‘\0‘) { cptr = chars; while (*cptr != ‘\0‘) { if (*cptr == *sptr) {
//找到打印source地址 printf("chars:0x%p\n", chars); //返回类型为 char *,此处类型转换一下把char const *转换回来 return (char *)cptr; } cptr++; } sptr++; } return NULL; }
#include <stdio.h> #include "function.h" int main() { char *source = "ABCDEF"; char *str1 = "XYZ"; char *str2 = "XRCQEF"; char *chars = str1; char *ptr = NULL; //没有对应的字符 ptr = find_char(source, chars); printf("0x%p\n", ptr); //对应的字符C,第三个 chars = str2; ptr = find_char(source, chars); printf("0x%p\n", ptr); while (1) ; return 0; }
执行结果:
6.2删除字符串中子串部分,将剩下部分前移。
int del_substr(char *str, char const *substr) { if (str == NULL || substr == NULL) { return 0; } //将数组首位赋值给指针数组 char *source = str; char *sub = substr; char *tmp = NULL; while (*source != ‘\0‘) { //将指针重置指向子串首 sub = substr; //使用临时变量进行对比,保持source位置信息不变 tmp = source; //当遇到相同的字符,开始比较之后是否相同 while (*tmp++ == *sub++) { //循环中已经sub++了,到达末尾,证明找到子串,开始前移 if (*sub == ‘\0‘) { //未到达字符串末尾,继续前移 while (*(tmp + 1) != ‘\0‘) { *source = *tmp; } return 1; } } source++; } return 0; }
int main() { char *source = "ABCDEF"; char *str1 = "CGE"; char *str2 = "CDE"; int isDel; //无子串 isDel = del_substr(source, str1); printf("del_substr: %d\n", isDel); //有子串 isDel = del_substr(source, str2); printf("del_substr: %d\n", isDel); while (1) ; return 0; }
执行结果:
6.3 编写函数reverse_string,翻转字符串。
void reverse_string(char *string) { //先定义两个指针,一个指向首一个指向末尾 char *head = string; //string本身指向第一位,加上字符串长度后是指向\0后的,所以需要前移,指向最后一个字符 char *tail = string + strlen(string) - 1; char tmp; //同一数组内可以进行指针位置对比 while (head < tail) { tmp = *head; *head = *tail; *tail = tmp; head++; tail--; } } int main() { char source[] = "ABCDEF"; printf("source: %s\n", source); reverse_string(source); printf("result: %s\n", source); return 0; }
执行结果:
6.4 erato法找质数
void find_primer(int *numbers, int length) { //0 1 不为质数 numbers[0] = FALSE; numbers[1] = FALSE; int tmp; int loc; int index = 2; while (index < length) { tmp = index; //大于二的偶数全不是质数,直接跳过 if (index > 2 && index % 2 == 0) { numbers[index] = FALSE; index++; continue; } //当前头部找到的质数,和后面的数相乘的结果对应的位置全部不是质数。 while ( (loc = tmp * index) < length) { *(numbers + loc) = FALSE; tmp++; } index++; } }
int main() { int numbers[10000]; for (int index = 0; index < 10000; index++) { numbers[index] = TRUE; } find_primer(numbers, 10000); for (int index = 0; index < 10000; index++) { if (numbers[index]) { printf("%-08d", index); } } return 0; }
运行结果:
标签:
原文地址:http://www.cnblogs.com/yangxunwu1992/p/5774722.html