字符串输入
gets()函数
这个函数在C11标准的时候已经被废除
所以 产生了gets()的替代品—fgets()函数
fgets()函数(这个用的比较多)
fgets()函数通过第2个参数限制读入字符的最大数量,通过第3个参数来指明要读入的文件.
s_gets()函数(这个函数我用的也不多)
自定义输入函数(这个函数是c prime plus里面的) — s_gets()
char *s_gets(char* st, int n)
{
char * ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val)
{
while (st[i] != '\n'&&st[i] != '\0')
i++;
if (st[i] == '\n')//如果输入中有换行符
{
st[i] = '\0';//让空字符去替代这个换行符
}
else
{
while (getchar() != '\n')//如果没有检测到换行符就会一直丢弃当前字符直到遇见换行符
{
continue;
}
}
}
return ret_val;
}
这个函数在fgets()的基础上进行改进,它丢弃了fgets()保留的换行符(用空字符代替),并且丢弃换行符后面的部分.(因为输入行中多出来的字符会留在缓冲区中,不丢弃的话会变成了下一次的输入)
scanf()函数
字符串输出
puts()函数会在字符串后面添加换行符 实现自动换行
printf()可以让输出按指定的格式来进行
fputs()在文件处理上用的比较多
字符串处理函数
字符串函数有很多,函数原型都在string.h中,这里我只分享自己目前用的比较多的几个
- 统计字符串长度
size_t strlen(const char* s);
返回s字符串中的字符数,不包括末尾的空字符.
- 拼接字符串
char* strcat(char* s1,char* s2);
把s2拼接到s1的屁股后面(s1的空字符会被覆盖),返回修改后的s1字符串
- 比较字符串
int strcmp(const char* s1,const* s2);
使用机器排序序列:
s1在s2的后面(比s2大),返回一个正数
s1与s2相等,返回0
s1在s2的前面(比s2小),返回一个负数
- 拷贝字符串
char *strcpy(char * s1,const *char s2);
把s2指向的字符串(就算是空的),拷贝到s1指向的位置,返回s1指向的字符串.
- 寻找特定字符
char * strchr(const char* s,char c)
如果字符串s中包含了字符c,返回值 就是一个指向c首次出现的位置的指针
如果里面没有c 返回值 就是一个空指针
字符串排序的示例
//读入字符串 并且排列字符串
#include<stdio.h>
#include<string.h>
#define SIZE 3
#define LIM 5
#define HALT ""
char *s_gets(char* st, int n);
void stsrt(char*string[], int num);
int main(void)
{
char input[LIM][SIZE];
char *ptstr[LIM];
int ct = 0;
int k;
printf("输出%d行,我将给他们排序:\n",LIM);
while (ct < LIM&&s_gets(input[ct], SIZE) != NULL && input[ct][0] != '\0')
{
ptstr[ct] = input[ct];
ct++;
}
stsrt(ptstr, LIM);
puts("这是新排列的:");
for (k = 0; k < ct; k++)
{
puts(ptstr[k]);
}
return 0;
}
char *s_gets(char* st, int n)//针对输入的处理函数
{
char * ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val)
{
while (st[i] != '\n'&&st[i] != '\0')
i++;
if (st[i] == '\n')
{
st[i] = '\0';
}
else
{
while (getchar() != '\n')
{
continue;
}
}
}
return ret_val;
}
void stsrt(char*string[], int num)//排序函数
{
//创建临时指针数组
char * temp;
//排序法则:比较两个字符串的开头的第一个字母(如果相同就往后延升)
for (int i = 0; i < num-1; i++)
{
for (int j =i+1; j < num; j++)
{
if (strcmp(string[i], string[j]) > 0)//如果第一个字符串比第二个前的话 就返回负数 相等就返回0 第一个比第二个大的话返回1 这个就是由小按大排
{
temp = string[i];
string[i] = string[j];
string[j] = temp;
}
}
}
}
//我的理解:这个是标准的排序算法 采用双层镶嵌结构 第二层用到第一层的参数
//思路是:让第一行与第一行后面的对比(比如有5个 5个比4个) 得到最小的行 然后变成第二行与第二行后面对比(4个比3个)
//字符串的内部对比是依赖于strcmp这个函数实现 如果完全一样就没必要换顺序 所以不进入循环比对