當前位置:編程學習大全網 - 編程語言 - C語言(unix)

C語言(unix)

//---------------------------------------------------------------------------

/*

* Program to parse a given sentence into words.

*/

#include <stdio.h>

#include <string.h>

// This function takes a character and a string

// as input and computes if the character is in

// the string or not. Returns 1 if yes, 0 otherwise.

int is_char_in_string(char c, char *s)

{

while (*s != '\0')

{

if (c == *s) return 1;

s++;

}

return 0;

}

main()

{

char line[255];

char delim[10] = " .,;!?"; // set of delimiting characters that can separate two words

int i;

int length;

int count=0;

// Get a line from user as input

printf("Enter a sentence: ");

gets(line);

// The line before we replace the delimiting characters with 0.

length = strlen(line);

for(i=0;i<length; ++i)

{

printf ("%3c ", line[i]);

}

printf("\n\n");

length = strlen(line);

//Replace delimiting characters with '\0'.

for(i=0;i<length; ++i)

{

if (is_char_in_string(line[i], delim))

line[i] = '\0';

}

// The line after we replace delimiting characters with 0.

for(i=0;i<length; ++i)

{

printf ("%3c ", line[i]);

}

printf("\n\n");

// Printing the line as integers so that we can see that space is

// replaced with 0.

for(i=0;i<length; ++i)

{

printf ("%3d ", line[i]);

}

printf("\n\n");

// Complete the program to count the number of words in the sentence and

// print each word separately, along with length of each word.

// If line = "Arizona is hot", your output should be

// Word 1: Arizona Length = 7

// Word 2: is Length = 2

// Word 3: hot Length = 3

for (i = 0; i<length;) {

printf("Word %d: %s Length = %d\n",++count,&line[i],strlen(&line[i]));

i+=strlen(&line[i])+1;

}

}

//---------------------------------------------------------------------------

  • 上一篇:地統計學的地統計模擬
  • 下一篇:web的版本區別
  • copyright 2024編程學習大全網