函式和字串排序
從主函式輸入十個不等長的字串,編寫函式,對這些串進行排序,在主調函式中輸出排好序的串。
1、利用指向一維陣列的指標來實現
#include <stdio.h>
#include <string.h>
#define N 10
int sort(char (*str)[10])
{
int i,j;
char temp[10];
for(i=0;i<N;i++)
{
for(j=i+1;j<N;j++)
{
if(strcmp(str[i],str[j])>0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
}
return 0;
}
int main()
{
char str[N][10];
int i;
for(i=0;i<10;i++)
gets(str[i]);
sort(str);
printf("the sorted result is:\n");
for(i=0;i<10;i++)
puts(str[i]);
return 0;
}
2、利用指標陣列實現:
#include <stdio.h>
#include <string.h>
#define N 10
int sort(char *ps[N])
{
int i,j;
char *temp;
for(i=0;i<N;i++)
{
for(j=i+1;j<N;j++)
{
if(strcmp(ps[i],ps[j])>0)
{
temp=ps[i],ps[i]=ps[j], ps[j]=temp;
}
}
}
return 0;
}
int main()
{
char str[N][10];
char *ps[N];
int i;
for(i=0;i<10;i++)
gets(str[i]);
for(i=0;i<N;i++)
ps[i]=str[i];
sort(ps);
printf("the sorted result is:\n");
//這種排序方式並沒有改變字串的內容
//只是改變了指標陣列的內容
//所以以下的結果不對
for(i=0;i<N;i++)
puts(str[i]);
//而以下的結果是對的
printf("true sorted result is:\n");
for(i=0;i<N;i++)
puts(ps[i]);
return 0;
}
3、利用指標陣列實現
#include <stdio.h>
#include <string.h>
#define N 10
int sort(char *ps[N])
{
int i,j;
char temp[10];
for(i=0;i<N;i++)
{
for(j=i+1;j<N;j++)
{
if(strcmp(ps[i],ps[j])>0)
{
strcpy(temp,ps[i]);
strcpy(ps[i],ps[j]);
strcpy(ps[j],temp);
}
}
}
return 0;
}
int main()
{
char str[N][10];
char *ps[N];
int i;
for(i=0;i<10;i++)
gets(str[i]);
for(i=0;i<N;i++)
ps[i]=str[i];
sort(ps);
//這種排序方式直接改變的是字串的內容
//所以以下結果都是對的
printf("the sorted result is:\n");
for(i=0;i<N;i++)
puts(str[i]);
printf("true sorted result is:\n");
for(i=0;i<N;i++)
puts(ps[i]);
return 0;
}
相關文章
- SQL中常用的字串LEFT函式和RIGHT函式詳解!SQL字串函式
- MySQL(四)日期函式 NULL函式 字串函式MySql函式Null字串
- Oracle 字串函式Oracle字串函式
- Oracle 字串函式Oracle字串函式
- 字串函式 metaphone ()字串函式
- 字串函式 print ()字串函式
- 字串函式 explode ()字串函式
- 字串函式 ord ()字串函式
- 字串函式 ltrim ()字串函式
- 字串函式 levenshtein ()字串函式
- 字串函式 lcfirst ()字串函式
- 字串函式 implode ()字串函式
- 字串函式 fprintf ()字串函式
- 字串函式 htmlentities ()字串函式HTML
- 字串函式 htmlspecialchars ()字串函式HTML
- PHP字串函式PHP字串函式
- MySQL 字串函式:字串擷取MySql字串函式
- PHP 每日一函式 — 字串函式 crypt ()PHP函式字串
- PHP 每日一函式 — 字串函式 chr ()PHP函式字串
- PHP 每日一函式 — 字串函式 addslashes ()PHP函式字串
- PHP 每日一函式 — 字串函式 addcslashes ()PHP函式字串
- MySQL函式學習(一)-----字串函式MySql函式字串
- T-SQL——函式——字串操作函式SQL函式字串
- 函式氣泡排序函式排序
- Python排序函式用法Python排序函式
- 7.PHP陣列和字串常用函式PHP陣列字串函式
- MySQL函式大全(字串函式,數學函式,日期函式,系統級函式,聚合函式)MySql函式字串
- Lesson12——NumPy 字串函式之 Part1:字串操作函式字串函式
- lambda匿名函式sorted排序函式filter過濾函式map對映函式函式排序Filter
- C++筆記— 排序函式sort() 和vector容器C++筆記排序函式
- 陣列排序函式-php陣列函式(一)陣列排序函式PHP
- 【Hive】字串替換函式translate和regexp_replaceHive字串函式
- Lesson14——NumPy 字串函式之 Par3:字串資訊函式字串函式
- python 的數值和字串和相關內建函式Python字串函式
- PHP 每日一函式 — 字串函式 chunk_split ()PHP函式字串
- PHP 每日一函式 — 字串函式 crc32 ()PHP函式字串
- PHP 每日一函式 — 字串函式 count_chars ()PHP函式字串
- 字串函式 md5 ()字串函式
- 字串函式學習三字串函式