字符串案列代码
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
char str[5] = {'h','e','l','l','o'};
char str1[5] = {'h','e','h','e'}; // \0
char str2[]= {'h','e','i','h','e','i'};
char str3[5]= {};
char str4[6]={"hello"};
//双引号所写的字符串,后面都隐含一个\0,叫做结束标志,该标志是由系统自行添加
// char str5[6] = "hello";
// char str6[6] = "he";
// char str7[] = "hello";
// char str8[6] = "";
char str9[1];
char * s ;
s = "how are you";
puts("请输入字符串:");
// scanf("%s",str9);
gets(str9);
printf("%s\n",str9);
puts(str9);
// printf("%ld\n",sizeof(str2));
// printf("%ld\n",sizeof(str7));
// printf("%ld\n",sizeof(str6));
// printf("%ld\n",strlen(str6));
}
return 0;
}
字符串string-Scanf
#import <Foundation/Foundation.h>
#import "string.h"
//输入一个字符串,统计字符串中数字字符和字母字符的个数
void count();
int main(int argc, const char * argv[])
{
@autoreleasepool {
// count();
// printf("%d\n",isalpha('1'));
// printf("%d\n",isnumber('k'));
// printf("%d\n",isupper('K'));
// printf("%d\n",islower('K'));
// printf("%c\n",toupper('q'));
// printf("%c\n",tolower('A'));
char ch[100]="avbadfadsfaba";
char a[100] = "ae";
printf("%s\n",strstr(ch, a));
// printf("%s\n",strrchr(ch, a));
// char cc[100];
// puts("请输入一个字符串:");
// gets(cc);
// int a = strcmp(ch, cc);
// printf("%d\n",a);
// strcat(ch, cc);
// strcpy(ch, cc);
// puts(ch);
// printf("%lu\n",strlen(gets(ch)));
}
return 0;
}
void count(){
char str[100];
int num=0,word=0;
puts("请输入一个字符串:");
gets(str);
for (int i=0; str[i]; i++) {
if ((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z')) {
word++;
}
if (str[i]>='0'&&str[i]<='9') {
num++;
}
}
printf("字母数量有:%d\n数字数量有:%d\n",word,num);
}
实现字符串函数
#import <Foundation/Foundation.h>
//my_strlen:计算字符串的长度
int my_strlen(const char * p);
//my_strcpy:字符串的复制
char * my_strcpy(char * buf1,const char * buf2);
//my_strcat:字符串的拼接
char * my_strcat(char * buf1,const char * buf2);
int main(int argc, const char * argv[])
{
@autoreleasepool {
char ch[100];
char str[100];
puts("请输入一个字符串:");
gets(ch);
puts("请再输入一个字符串:");
gets(str);
my_strcat(ch, str);
// my_strcpy(ch, str);
puts(ch);
// printf("%d\n",my_strlen(ch));
}
return 0;
}
//my_strlen:计算字符串的长度
int my_strlen(const char * p){
int i;
for (i=0; p[i]; i++) ;//遍历字符串找到\0的位置即此字符串的长度
return i;
}
//my_strcpy:字符串的复制
char * my_strcpy(char * buf1,const char * buf2){
int i;
//遍历字符串2
for (i=0; buf2[i]; i++) {
buf1[i] = buf2[i]; //将字符串2的内容依次赋值到字符串1中
}
buf1[i] = buf2[i];//将字符串2的\0赋值到字符串1的最后位置
return buf1;
}
//my_strcat:字符串的拼接
char * my_strcat(char * buf1,const char * buf2){
int i,j;
for (i=0; buf1[i]; i++); //找出第一个字符串中的\0的位置
//遍历第二个字符串
for (j=0; buf2[j]; j++) {
buf1[i+j]=buf2[j]; //将第二个字符串的字符依次赋值到第一个字符串\0的位置
}
buf1[i+j]=buf2[j];//将第二个字符串中的\0赋值到第一个字符串最后的位置
return buf1;
}