程式扎記: [C 範例代碼] 基礎知識 : 在指定位置後插入字符串

標籤

2010年11月16日 星期二

[C 範例代碼] 基礎知識 : 在指定位置後插入字符串

前言 : 
使用者首先輸入兩個字串a 和 b, 再輸入數值來確定將字符串2 插在字符串哪個字符後面, 最後將插入後的字符串輸出. 

技術要點 : 
這個例子使用到許多字符串處理函數, 簡單介紹如下 : 
* C++ : Reference : C Library : cstring (string.h) : strcpy 

char * strcpy ( char * destination, const char * source );
Copy string
Copies the C string pointed by source into the array pointed by destinationincluding the terminating null character.
To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source
. 
* C++ : Reference : C Library : cstring (string.h) : strncpy 
char * strncpy ( char * destination, const char * source, size_t num );
Copy characters from string
Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.
No null-character is implicitly appended to the end of destination, so destination will only be null-terminated if the length of the C string in source is less than num.

* C++ : Reference : C Library : cstring (string.h) : strcat 
char * strcat ( char * destination, const char * source );
Concatenate strings
Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a new null-character is appended at the end of the new string formed by the concatenation of both in destination.


範例代碼 : 
  1. #include   
  2. #include   
  3. char* insert(char s[], char t[], int i) {  
  4.     char string[100];  
  5.     int len = strlen(s);  
  6.     if(len<=0 || i>len) {  
  7.         printf("Error!\n");  
  8.         exit(1);  
  9.     }  
  10.     if(len == 0) {  
  11.         strcpy(s, t);  
  12.     } else {  
  13.         strncpy(string, s, i);  
  14.         string[i] = '\0';  
  15.         strcat(string, t);  
  16.         strcat(string, s+i);  
  17.         strcpy(s, string);  
  18.     }  
  19.     return s;  
  20. }  
  21.   
  22. void main() {  
  23.     char a[100] = {0};  
  24.     char b[100] = {0};  
  25.     int position;  
  26.     printf("Please input str1: ");  
  27.     gets(a);  
  28.     printf("Please input str2: ");  
  29.     gets(b);  
  30.     printf("Please input insertion position: ");  
  31.     scanf("%d", &position);  
  32.     insert(a, b, position);  
  33.     printf("Result: %s\n", a);  
  34. }  

執行結果 : 
Please input str1: Hi Lee <中間有兩個空白>
Please input str2: John
Please input insertion position: 3
Result: Hi John Lee

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!