1、字符串左中右
1 #include<stdio.h> 2 #include <string.h> 3 #define N 100 4 5 void Left(char src[], int n, char dest[]); 6 void Right(char src[], int n, char dest[]); 7 void Mid(char src[], int loc, int n, char dest[]); 8 int main() 9 { 10 int n,loc; 11 char src[N] = ""; 12 char dest[N] = ""; 13 scanf("%s",src); 14 scanf("%d%d",&n,&loc); 15 16 Left(src,n,dest); 17 Right(src,n,dest); 18 Mid(src,loc,n,dest); 19 return 0; 20 } 21 void Left(char src[], int n, char dest[]){ 22 strncpy(dest,src,n); 23 printf("%s ",dest); 24 } 25 void Right(char src[], int n, char dest[]){ 26 int len = strlen(src); 27 strcpy(dest,&src[len-n]); 28 printf("%s ",dest); 29 } 30 void Mid(char src[], int loc, int n, char dest[]){ 31 strncpy(dest,&src[loc],n); 32 printf("%s ",dest); 33 }
2、分离单词
1 #include<stdio.h> 2 #include <string.h> 3 #define N 256 4 5 int main() 6 { 7 char str[N] = ""; 8 char s[N] = ""; 9 int count = 0; 10 gets(str); 11 12 /* 从字符串str尾部逐个截取单词连接到字符串s*/ 13 for(char *p = str + strlen(str)-1; p>=str-1; p--) 14 { 15 if(*p>='a'&&*p<='z'||*p>='A'&&*p<='Z'){ 16 count++; 17 } 18 else{ 19 if(*(p+1)>='a'&&*(p+1)<='z'||*(p+1)>='A'&&*(p+1)<='Z'){ 20 strncat(s,(p+1),count); 21 strcat(s," "); 22 } 23 count=0; 24 } 25 } 26 27 puts(s);/* 输出 */ 28 29 return 0; 30 }
3、删除字符
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include <string.h> 4 #define N 100 5 void deletechar(char s[],char c); 6 int main() 7 { 8 char s[N] = "", c; 9 gets(s); 10 c = getchar(); 11 deletechar(s,c); 12 puts(s); 13 return 0; 14 } 15 void deletechar(char s[],char c){ 16 char t[N] = ""; 17 char *p = s, *q = t; 18 while(*p) 19 { 20 if(*p!=c) 21 *q++ = *p; 22 p++; 23 } 24 strcpy(s,t); 25 }
4、字符串复制
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include <string.h> 4 #define N 100 5 void copy(char s1[],char s2[], int m); 6 int main() 7 { 8 char s1[N] = "", s2[N] = ""; 9 int m; 10 gets(s1); 11 scanf("%d",&m); 12 13 copy(s1,s2,m); 14 puts(s2); 15 return 0; 16 } 17 void copy(char s1[],char s2[], int m){ 18 strcpy(s2,&s1[m]); 19 }
5、Music Composer
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include <string.h> 4 #define N 100 5 6 int main() 7 { 8 char key[10][3] = {"A#","Bb","C#","Db","D#","Eb","F#","Gb", "G#", "Ab"}; 9 char s1[N] = "", s2[N] = ""; 10 scanf("%s%s",s1,s2); 11 12 if(strlen(s1)==1) 13 strcpy(s1,"UNIQUE"); 14 else{ 15 for(int i=0; i<10; ++i) 16 { 17 if(!strcmp(s1,key[i])){ 18 if(i%2) i--; 19 strcpy(s1,key[i]); 20 break; 21 } 22 } 23 puts(strcat(strcat(s1," "),s2)); 24 } 25 return 0; 26 }
6、字符串逆序
1 #include<stdio.h> 2 #define N 100 3 /* 不让用字符串处理函数 */ 4 int main() 5 { 6 char s[N] = ""; 7 gets(s); 8 /* 计算字符串长度 */ 9 int i; 10 for(i=0; s[i]!='='; ++i); 11 /* 去掉字符串中的=字符 */ 12 char *p = s, *q = s + i; 13 *q-- = '