- 輸入以下字串,並以空格切斷,分切並儲存於字串陣列,再將字串陣列顯示出來。
- 將字串依ASCII值排序。
- 依程式功能設計幾個function,以下程式碼為示意。
I believe we should be working towards a world where people can speak privately and live freely knowing that their information will only be seen by who they want to see it and won't all stick around forever.
使用到 cin.getline 、 strlen 、memset 函數
cin.getline
getline (char* s, streamsize n );
getline (char* s, streamsize n, char delim );
輸入至多 n 個字符(包含結束標記符)保存在 s 對應的字串中。
即使還沒讀夠n個字符,用來讓使用者自行輸入一串文字
strlen
size_t strlen(const char *str)可以計算字串的長度
memset
void *memset(void *str, int c, size_t n)用於將 c 複製到 str n 表示複製個數
#include <iostream>
#include <cstring>
void input_string( char str[], int maxlength ) // input_string( char *str )
{
std::cout << "Please enter string:" << std::endl;
std::cin.getline( str, maxlength );
std::cout << std::endl;
}
void output( char array[][20], int num )
{
for ( int i=0; i < num; i++ )
if ( strlen(array[i]) > 0 )
std::cout << "[" << i << "]" << array[i] << std::endl;
}
int parse( char str[], char array[][20] )
{
int i=0, j=0;
char *ptr = str;
while ( *ptr != '\0' ) {
if ( *ptr == ' ' )
{
array[i][j] = '\0';
i++;
j=0;
}
else
{
//printf("%c", *ptr);
array[i][j] = *ptr;
j++;
}
ptr++;
}
return i+1;
}
int compare( char str1[], char str2[] )
{
int len1 = strlen(str1);
int len2 = strlen(str2);
int result = 0;
for ( int i=0; (i < len1) && (i < len2); i++ ) {
result = str1[i] - str2[i] ;
if ( result != 0 ) return result;
}
return len1 - len2;
}
void swap( char str1[], char str2[] , int size )
{
char temp;
for ( int i=0; i < size; i++ ) {
temp = str1[i];
str1[i] = str2[i];
str2[i] = temp;
}
}
void sort( char array[][20], int count )
{
char temp[20];
for ( int j=0; j<count-1; j++ )
for ( int i=j+1; i<count; i++ )
if ( compare( array[j], array[i] ) > 0 )
swap( array[j] , array[i], 20 );
}
int main(int argc, char** argv)
{
char input[1024];
char strarray[50][20];
int count = 0;
memset( strarray, 0, sizeof(strarray) );
input_string( input, sizeof(input) );
count = parse( input , strarray );
sort( strarray, count );
output( strarray, 50 );
return 0;
}
沒有留言:
張貼留言