C语言简单冒泡排序法:
#include <stdio.h>
int main(void)
{
int a[] ={900,2,3,888,1000};
int n;
int i;
int j;
int buf;
n = sizeof(a)/sizeof(a[0]);// /*a[0]是int型, 占4字节, 所以总的字节数除以4等于元素的个数*/
for(i = 0;i<n-1;++i)
{
for(j = 0;j<n-1-i;++j)
{
if(a[j]<a[j+1])
{
buf = a[j];
a[j] = a[j+1];
a[j+1] = buf;
}
}
}
for(i = 0;i<n;++i)
printf("%d\n",a[i]);
return 0;
}
/***************
/* 字符串分割
/***************
#include <stdio.h>
#include <string.h>
int main()
{
char *str = strdup("listen love mm");//strdup在内部调用了malloc()为变量分配内存,
//不需要使用返回的字符串时,需要用free()释放相应的内存空间,否则会造成内存泄漏。
char *p;
p = strsep(&str," ");//第一个参数,指向字符串的指针;
//第二个参数,分割的标志字符
while(p!=NULL)
{
printf( "%s\n ",p);
p = strsep(&str," ");
}
free(str);
return 0;
}
C语言实现字符串反转
#include <stdio.h>
#include <string.h>
void reverse(char* str)
{
char* p = str + strlen(str)-1;//指导指针p移到字符串str的最后一个字符的地址上,此时值为n
char temp;
printf("%s\n",p);
while(str<p)//在未完成倒序前,p指向的地址始终大于str
{
temp=*p;
*p--=*str;//f分步:*p = *str;*p--;
printf("%s\n",p);
*str++=temp;
}
}
int main()
{
char *str = strdup("listen");
reverse(str);
printf("翻转后的字符串是:\n%s\n", str);
return 0;
}