前言 :
使用者首先輸入兩個字串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 destination, including 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.
範例代碼 :
- #include
- #include
- char* insert(char s[], char t[], int i) {
- char string[100];
- int len = strlen(s);
- if(len<=0 || i>len) {
- printf("Error!\n");
- exit(1);
- }
- if(len == 0) {
- strcpy(s, t);
- } else {
- strncpy(string, s, i);
- string[i] = '\0';
- strcat(string, t);
- strcat(string, s+i);
- strcpy(s, string);
- }
- return s;
- }
-
- void main() {
- char a[100] = {0};
- char b[100] = {0};
- int position;
- printf("Please input str1: ");
- gets(a);
- printf("Please input str2: ");
- gets(b);
- printf("Please input insertion position: ");
- scanf("%d", &position);
- insert(a, b, position);
- printf("Result: %s\n", a);
- }
執行結果 :
Please input str1: Hi Lee <中間有兩個空白>
Please input str2: John
Please input insertion position: 3
Result: Hi John Lee
沒有留言:
張貼留言