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;
}