2.7 类型转换
下面的函数atoi,将一串数字转换为相应的数值
int atoi(char s[])
{
int i,n;
n = 0;
for (i = 0; s[i]>='0' && s[i] <= '9' ; ++i) {
n = 10 * n +(s[i] - '0');
}
return n;
}
函数lower:将char类型转换为int类型的函数,它将ASCII字符集中的字符映射到对应的小写字母。如果带转换的字符不是大写字母,lower函数将返回字符本身。
int lower(int c)
{
if(c >= 'A' && c <= 'z'){
c= c + 'a'-'A';
return c;
}
else {
return c;
}
}
rand函数,返回取值为0~32767的伪随机数
#include <stdio.h>
#include <stdlib.h>
unsigned long int next = 1;//定义外部变量next
int rand(void);//声明rand函数
void srand(unsigned int seed);//声明srand函数
int main()
{
int c,m;
c=rand();
m=rand();
printf("%d %d",c,m);
}
/*rand函数,返回取值为0~32767的伪随机数*/
int rand(void)
{
next = next * 1103515245 + 12345;
return (unsigned int)(next/65526) % 32768;
}
/* srand函数,为rand函数设置种子数*/
void srand(unsigned int seed)
{
next = seed;
}
从字符串s中删除字符c
void squeeze(char s[],int c)
{
int i,j;
for (i = j = 0; s[i] != '\0' ; i++) {
if(s[i] != c)
s[j++] = s[i];
}
s[j] = '\0';
}
将该函数放入调试运行
#include <stdio.h>
void squeeze(char s[],int c);
int main()
{
int i;
int c='O';
char a[10]={'I','L','O','V','E','Y','O','U'};
squeeze(a,c);
for (i = 0; i < 10; i++) {
printf("%c",a[i]);
}
}
void squeeze(char s[],int c)
{
int i,j;
for (i = j = 0; s[i] != '\0' ; i++) {
if(s[i] != c)
s[j++] = s[i];
}
s[j] = '\0';
}
标准函数strcat(s,t),将字符串t连接到字符串s中的尾部。
#include <stdio.h>
void strcat(char s[],char t[]);
int main()
{
int i;
char a[20]={'I','L','O','V','E','Y','O','U'};
char b[10]={'Y','O','U','L','O','V','E','M','E'};
strcat(a,b);
for (i = 0; a[i] != '\0'; i++) {
printf("%c ",a[i]);
}
}
void strcat(char s[],char t[])
{
int i,j;
i=j=0;
while(s[i] != '\0')
i++;
while ((s[i] = t[j]) != '\0')
{
j++;
i++;
}
}
getbits函数:返回x中从p开始的n位
这个函数本人没懂,故引用一位大佬的文章。🤩@枯荣有常
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
unsigned getbits(unsigned x, int p, int n)
{
return (x >> (p + 1 - n)) & ~(~0 << n);
}
int main() {
int x = 127, x1;
printf("x=%x\n", x);
x1 = getbits(x, 4, 3);
printf("getbits(x1)=%x\n", x1);
return 0;
}