C语言学习记录
前言
一直自己没有学习做笔记的习惯,所以为了加强自己对知识的深入理解,决定将学习笔记写下来,希望向各位大牛们学习交流!
不当之处请斧正!在此感谢!这边就先从学习C语言写起,自己本身对程序语言方面不擅长,所以决定对此从基础开始学习,
大牛们对此文可以忽略!
学校OJ实验
英文单词排序
Problem Description
输入若干有关颜色的英文单词(单词数小于150,每个单词不超过20个字母),每行一个,以#作为输入结束标志,对这些单词按照长度从小到大排序后输出。
程序编写要求:用动态分配的方式处理多个字符串的输入,用指针数组组织这些字符串并排序。
Input Description
输入有多行,每行一个有关颜色的英文单词,输入#时结束。
Output Description
在一行中输出排序后的结果,每个单词之间以一个空格分隔,最后一个后面没有空格。
Sample Input
blue
red
yellow
green
purple
#
Sample Output
red blue green yellow purple
解题:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sort(char *name[], char *m[], int n);
void print(char *name[],int n);
int main()
{
int i=0, j=0;
char *a[150], *b[150];
a[i] = (char*)malloc(sizeof(char)*21); //申请内存
b[i] = (char*)malloc(sizeof(char)*21);
while( scanf("%s", a[i++]) ) //输入字符串
{
if(*a[i-1] == '#')
{
break;
}
strcpy(b[j++],a[i-1]);
a[i] = (char*)malloc(sizeof(char)*21);
b[i] = (char*)malloc(sizeof(char)*21);
}
sort(a, b, j);
print(a, j);
return 0;
}
void sort(char *name[], char *m[], int n) //排序
{
char *temp;
int i, j, k, g, p;
for(i=0;i<n-1;i++)
{
k=i;
for(j=i+1;j<n;j++)
{
//if(strcmp(name[k],name[j])>0) k=j;
if(strlen(name[k]) > strlen(name[j])) //每次找出最短字符串
{
k=j;
}
else if(strlen(name[k]) == strlen(name[j])) //若相等判断谁先输入则谁在前面
{
for(g=0; g<n; g++)
{
if(strcmp(name[k],m[g]) == 0)
{
break;
}
}
for(p=0; p<n; p++)
{
if(strcmp(name[j],m[p]) == 0)
{
break;
}
}
if(g > p) k=j;
}
else
{
}
}
if(k !=i ) //交换
{
temp=name[i];
name[i]=name[k];
name[k]=temp;
}
}
}
void print(char *name[],int n) //格式化输出
{
int i;
for(i=0;i<n;i++)
if(i == 0)
{
printf("%s",name[i]);
}
else
{
printf(" %s",name[i]);
}
putchar('\n');
}
若要求查找最长的单词
则代码改为:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int read_color(char **color);
char **find_max_len(const char **s, int n);
int main()
{
int n; //字符串个数
char *color[150], **ans;
n = read_color(color); //读入字符串,并把字符串的首地址存入指针数组color[],返回数组的长度
ans = find_max_len(color, n); //查找最长的单词,返回指向第一个最长单词的指针数组元素的指针
printf("%s\n", *ans);
return 0;
}
int read_color(char **color) //输入字符串
{
int i=0;
color[i] = (char*)malloc(sizeof(char)*21);
while( scanf("%s", color[i++]) )
{
if(*color[i-1] == '#')
{
//free(a[i-1]);
break;
}
//strcpy(b[j++],a[i-1]);
//j++;
color[i] = (char*)malloc(sizeof(char)*21);
}
return i;
}
char **find_max_len(const char **s, int n) //找到最长字符串
{
int i, j, max=0;
const char **an = malloc(120);
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(strlen(s[max]) < strlen(s[j]))
{
max=j;
}
else if(strlen(s[max]) == strlen(s[j]))
{
if(j < max)
max = j;
}
else{}
}
}
an = &s[max];
return an;
}