题目:有一段文本,将文本中的所有单词,存放到一个字符指针数组中(要求每个单词内存恰好)。
第一种做法
char c[] = " asd afil kjgl rip kjgdr gds sdg gs ";
char b[10] = {0};
char *a[10] = {NULL};
int i = 0, j = 0,k = 0; //i使字符不断后移,j用来标识指针a,k用来标识中间字符数组b;
while (1) {//把字符串的‘\0‘ 作为if判断的条件,避免遇到\0不在判断
if (c[i] != ‘ ‘ && c[i] != ‘\0‘) {
b[k++] = c[i++];
continue; //提高效率,当进行此if判断时,就不在进行一下if判断
}
if ((c[i] == ‘ ‘ || c[i] == ‘\0‘) && k != 0) {
//k判断是否有字符赋给b数组,没有的话意味着前面是空空格,就不在需要进行判断,提高运行效率
b[k] = ‘\0‘; //给数组b加上\0 ,结束字符
a[j] = malloc(strlen(b) + 1); //为指针开辟空间
strcpy(a[j], b); //b是首地址,a[j]也是首地址,函数具有复制功能,如:%s
k = 0;
j++;
}
if (c[i] == ‘\0‘) { //把while中的\0判断移到可以先判断\0的情况
break;
}
i++;
}
for (int i = 0 ; i < j ; i++ ) {
printf("%s\n", a[i]); //int a = 10; int *b = null; b = &a; *b = 10;
free(a[i]); //* 具有指向功能,
a[i] = NULL;
}
第二种做法
char str[] = " a41 a1421 b3511 b b c c c c dddddd jkthku";
//2.如何存储一个单词?
char tempStr[20] = {0}; //存储文本中的一个单词
//3.如何存储堆区空间的地址?
char *p[255] = {0};
//4.如何查找单词,并且将对应的单词存放到临时数组中?
int i = 0; //标识str字符串中字符的下标
int j = 0; //标识tempStr字符串中字符的下标
int k = 0; //标识指针数组中元素的下标.
while (1) {
if (str[i] != ‘ ‘ && str[i] != ‘\0‘) {
//当获取到的元素不为空格时,将它存储到临时数组tempStr中.
tempStr[j++] = str[i];
} else if (j != 0) {
//当遇到空格,或者遇到\0时.单词的存放结束
tempStr[j] = ‘\0‘; //最后一个元素补上\0
//动态计算所需堆区空间的大小,将地址存放到对应的字符指针数组元素中
p[k] = malloc(strlen(tempStr) + 1);
//将临时数组tempStr中字符串拷贝到对应堆区空间上.
strcpy(p[k], tempStr);
k++;
j = 0; //存储下一单词时,又从数组的第一个字符开始.
}
//当读取到\0时,字符串读取完毕,跳出循环
if (str[i] == ‘\0‘) {
break;
}
i++; //移动到str数组中的下一个元素
}
for (int i = 0; i < k; i++) {
printf("%s ", p[i]);
free(p[i]);
p[i] = NULL;
}
第三种做法
char str[50] =" qwo shi shui nishi hhdj";
char temp[20] = {0};
char *p[10] = {0};
int count = 0;
int d = 0,i = 0,index = 0,h = 0;
while (str[i] != ‘\0‘) {
if (str[i] != ‘ ‘) {
count ++;
i ++;
index = i - count;
}
if (str[i] == ‘ ‘ || str[i] == ‘\0‘ ){
if (count != 0) {
int k = 0;
for (int j = index; j < i;j ++) {
temp[k] = str[j];
k ++;
d = k;
}
temp[k] = ‘\0‘;
printf("%s\n",temp);
p[h] = malloc(count + 1);
strcpy(p[h], temp);
h ++;
count = 0;
}
i ++;
}
}
for (int i = 0; i < h; i ++) {
printf("%s ",p[i]);
free(p[i]);
p[i] = NULL;
}
第四种做法
char a[] = " The end of the World Cup does not mean the end of international competition in Brazil this year";
char *p[100] = {0}; //记录单词
char temp[100] = {0}; //临时记录单词
int i = 0; //记录a[]数组元素的位置
int j = 0; //记录单词的个数
int k = 0; //记录temp[]数组中临时单词的字母个数(元素位置)
int count = 0;
while (a[i] != ‘\0‘) {
if ((a[i] >= ‘a‘ && a[i] <= ‘z‘) || (a[i] >= ‘A‘ && a[i] <= ‘Z‘)) {
count++;
temp[k] = a[i];
k++;
} else if (k != 0) {
temp[k] = ‘\0‘;
k = 0;
p[j] = malloc(sizeof(char) * count + 1);
strcpy(p[j], temp);
printf("%s ", p[j]);
free(p[j]);
p[j] = NULL;
j++;
count = 0;
}
if (a[i + 1] == ‘\0‘ && a[i] != ‘ ‘) {
temp[k] = ‘\0‘;
k = 0;
p[j] = malloc(sizeof(char) * count + 1);
strcpy(p[j], temp);
printf("%s ", p[j]);
free(p[j]);
p[j] = NULL;
}
i++;
}
over
动态分配内存输出文本中的单词的四种做法,布布扣,bubuko.com
原文地址:http://chenhongyi.blog.51cto.com/9168548/1532578