1、字符串输入
1 #include <stdio.h>
2 #include <stdlib.h> //函数malloc()
3 #include <string.h>
4
5 int main()
6 {
7 int i = 0;
8 char *tempString;
9 char *stringArray[3]; //指针数组
10 for(i = 0; i < 3; i++)
11 {
12 printf("Enter: ");
13 scanf("%s", tempString); //输入
14 //malloc() 在 堆中 申请内存空间
15 stringArray[i] = (char *)malloc(sizeof(char) * (strlen(tempString) + 1));
16 strcpy(stringArray[i], tempString); //复制 字符串
17 }
18 printf("%s %s%s\n", stringArray[0], stringArray[1], stringArray[2]);
19 for(i = 0; i < 3; i++)
20 {
21 free(stringArray[i]); //free() 释放
22 }
23 return 0;
24 }
执行:
2、字符串长度
1 #include<stdio.h>
2
3 int main(int argc, char *argv[])
4 {
5 printf("string: %s\n", argv[1]); //输入的第一个参数
6 printf("length: %d\n", string_length(argv[1]));
7
8 return 0;
9 }
10
11 int string_length(char *str)
12 {
13 int str_len = 0;
14 char *temp = NULL;
15 temp = str;
16 while( *temp != '\0')
17 {
18 str_len++; //长度 自加
19 temp++;
20 }
21 return str_len;
22 }
执行:
3、字符串连接
1 #include <stdio.h>
2
3 char *stringCatenate(char *dest_str, char *src_str);
4
5 int main(int argc, char *argv[])
6 {
7 printf("%s\n", stringCatenate(argv[1], argv[2]));
8
9 return 0;
10 }
11
12 char *stringCatenate(char *dest_str, char *src_str)
13 {
14 char *dtemp = NULL;
15 char *stemp = NULL;
16 dtemp = dest_str;
17 stemp = src_str;
18 while(*dtemp != '\0')
19 {
20 dtemp++;
21 }
22 while(*stemp != '\0')
23 {
24 *dtemp = *stemp;
25 dtemp++;
26 stemp++;
27 }
28 *dtemp = '\0';
29 return dest_str; //注意:此处不是返回 dtemp
30
31 }
执行:
4、字符串复制
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 void stringCopy(char *dest_str, char *src_str);
5 int stringLength(char *str);
6
7 int main(int argc, char *argv[])
8 {
9 char *dest_str = NULL;
10 printf("source string: %s\n", argv[1]);
11 dest_str = (char *)malloc(sizeof(char) * (stringLength(argv[1]) + 1));
12 stringCopy(dest_str, argv[1]);
13 printf("back-up copy: %s\n", dest_str);
14 return 0;
15 }
16
17 //___复制
18 void stringCopy(char *dest_str, char *src_str)
19 {
20 char *dtemp = dest_str;
21 char *stemp = src_str;
22 while(*stemp != '\0')
23 {
24 *dtemp = *stemp;
25 dtemp++;
26 stemp++;
27 }
28 *dtemp = '\0';
29 }
30
31 //___长度
32 int stringLength(char *str)
33 {
34 char *temp = str;
35 int len = 0;
36 while(*temp != '\0')
37 {
38 len++;
39 temp++;
40 }
41 return len;
42 }
执行: