指针与字符串
#include <stdio.h>
int main()
{
char ch[] = "hello world";
char* p = ch;
printf("%s\n", ch);
for (int i = 0; i < sizeof(ch) 1; i )
{
if (*(p i) == " ")
{
continue;
}
if (*(p i) == "\n")
{
break;
}
printf("%c\n", *(p i));
}
return 0;
}
运行结果:
hello world
h
e
l
l
o
w
o
r
l
d
#include <stdio.h>
int main()
{
char ch[]="hello world";//栈区字符串
char* p="hello world";//数据区**常量**字符串(字符串函数数组)
char* p1="hello world";//p与p1所指对象一样
printf("%p\n",p);
printf("%p\n",p1);
return 0;
}
字符串处理函数
指针数组做main函数形参
main函数是操作系统调用的,第一个参数标明argc数组成员数量,argv数组的每个成员都是char*类型
argv是命令行参数的字符串数组
argc代表命令行参数的数量,程序名字本身算一个参数
#include <stdio.h>
#include <cstdlib>//里面定义了EXIT_SUCCESS
//gcc-o hello hello.c(4个参数"gcc","-o","hello","hello.c")
//int argc 表示传递参数的个数
//char* argv[]={"gcc","-o","hello","hello.c"}//表示参数具体内容
int main(int argc, char* argv[])
{
if (argc < 3)
{
printf("缺少参数:\n");
return -1;
}
for (int i = 0; i < argc; i )
{
printf("%s\n", argv[i]);
}
return EXIT_SUCCESS;
}
运行结果:
缺少参数
字符串出现的次数
字符串中各个字母出现的次数:
#include <stdio.h>
int main()
{
char ch[] = "helloworldnichoushachounizaidzaichouyigeshishi";//97 97 26
//存储字符串出现字数
int arr[26] = { 0 };
for (int i = 0; i < strlen(ch); i )
{
arr[ch[i] - 'a'] ;
}for (int i = 0; i < 26; i )
{
if (arr[i])
{
printf("字母:%c出现的次数:%d\n", i 'a', arr[i]);
}
}
return 0;
}
字母:a出现的次数:3
字母:c出现的次数:3
字母:d出现的次数:2
字母:e出现的次数:2
字母:g出现的次数:1
字母:h出现的次数:7
字母:i出现的次数:7
字母:l出现的次数:3
字母:n出现的次数:2
字母:o出现的次数:5
字母:r出现的次数:1
字母:s出现的次数:3
字母:u出现的次数:3
字母:w出现的次数:1
字母:y出现的次数:1
字母:z出现的次数:2
字符串逆置
#include <stdio.h>
#include <string.h>
void inverse(char* ch)
{
int i = 0;
int j = strlen(ch) - 1;
while (i < j)
{
char temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
i ;
j--;
}
return;
}
int main()
{
char ch[] = "hello world";
inverse(ch);
printf("%s\n", ch);
return 0;
}
字符串拷贝
字符串追加
字符串比较
字符串格式化
字符串查找
字符串类型转化