Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Exercise 79

C Exercise 79

100 Classic C Language Examples 100 Classic C Language Examples

**Problem:** Sort strings.

**Analysis:** None.

Program source code:

Example

// Created by www.runoob.com on 15/11/9.

// Copyright (c) 2015 Runoob Tutorial. All rights reserved.

#include

<

stdio.h

#include

<

stdlib.h

#include

<

string.h

#define

MAX_LEN

20

// Define a constant representing the maximum length of a string

// Function declaration: used to swap two strings

void

swap

(

char

str1

,

char

str2

)

;

int

main

(

)

{

char

str1

[

MAX_LEN

]

,

str2

[

MAX_LEN

]

,

str3

[

MAX_LEN

]

;

// Prompt the user to enter strings

printf

(

"

Please enter 3 strings, each ending with Enter:

\

n

"

)

;

// Use fgets to read input and remove the newline character

fgets

(

str1

,

sizeof

(

str1

)

,

stdin

)

;

str1

[

strcspn

(

str1

,

"

\

n

"

)

]

= '\

0

';

// Remove the newline character

fgets

(

str2

,

sizeof

(

str2

)

,

stdin

)

;

str2

[

strcspn

(

str2

,

"

\

n

"

)

]

= '\

0

';

// Remove the newline character

fgets

(

str3

,

sizeof

(

str3

)

,

stdin

)

;

str3

[

strcspn

(

str3

,

"

\

n

"

)

]

= '\

0

';

// Remove the newline character

// Sort the strings

if

(

strcmp

(

str1

,

str2

)

0

)

swap

(

str1

,

str2

)

;

if

(

strcmp

(

str2

,

str3

)

0

)

swap

(

str2

,

str3

)

;

if

(

strcmp

(

str1

,

str2

)

0

)

swap

(

str1

,

str2

)

;

// Output the sorted result

printf

(

"

The sorted result is:

\

n

"

)

;

printf

(

"

%s

\

n%s

\

n%s

\

n

"

,

str1

,

str2

,

str3

)

;

return

0

;

}

// Swap the contents of two strings

void

swap

(

char

str1

,

char

str2

)

{

char

temp

[

MAX_LEN

]

;

strcpy

(

temp

,

str1

)

;

// Copy str1 to the temporary string temp

strcpy

(

str1

,

str2

)

;

// Copy str2 to str1

strcpy

(

str2

,

temp

)

;

// Copy temp to str2

}

The above example produces the following output:



请输入3个字符串,每个字符串以回车结束!:

b

a

t

The sorted result is:

a

b

t

100 Classic C Language Examples 100 Classic C Language Examples