c++ string转unsigned char *_C|8个有趣有料也有点烧脑的编程小实例

编程也可以是一件很有趣的事情,虽然有时有点烧脑。

1 不使用算术运算符或比较运算符的情况下检查两个数字是否相等

int compl(int a, int b){if(a^b)return 1;elsereturn 0; // 两个相等的数字,XOR运算符返回0}
4e018909714ed91f8100f3eeb2a95387.png

2 不使用循环,打印1-10

#include #include #include using namespace std;string randStr(int n, int m){string str;srand((unsigned)time(NULL));for(int i=0;i>n>>m;string str=randStr(n,m);cout<

3 不使用共用体简单判断大小端

int endian(){unsigned int i=1;char* ch = (char*)&i;return *ch;}
547620d3cd9000c6b53704fd5dcf354f.png

4 不考虑ASCII编码的简单的大小写转换

char toLower(char ch){return (ch^32); // 异或表示不考虑进位(每位)的加法,因没有进位,+32}char toUpper(char ch){return (ch^32);  // 因有进位,不考虑,-32}

或:

return (ch^('a'-'A'));

5 幽它一默关机小程序

#include #include #include int main(){char write[24]={0};printf("快说我爱凤姐,不然两分钟内关机!");system("shutdown -s -t 120");label:scanf("%s",write);if(strcmp(write,"我爱凤姐")==0){printf("哈哈,你这个变态~");system("shutdown -a");system("pause");}else{printf("不想说?等着关说明吧!");goto label;}return 0;}
c7c966ac3b996cdea4a04b9a5d95a79e.png

6 生成随机字符串

aa12097aa765dfc442fc5625081f65fe.png
#include #include #include using namespace std;string randStr(int n, int m){string str;srand((unsigned)time(NULL));for(int i=0;i
1941eba904feef618ff4a0822a5c25e0.png

7 从子字符串处截断

#include "stdio.h"#include "string.h"char *mystrstr(const char *str1, const char *str2){char *src,*sub;if(str1 == NULL || str2 == NULL){printf("The string is error!");exit(0);}while(*str1 != '0'){src = str1;sub = str2;do{if(*sub == '0'){return str1;    /*找到子串*/}}while(*src++ == *sub++);str1++;}return NULL;}void main() {char str1[] = "This is a test,how to find!";char str2[] = "test", * pos;printf("str1: %s",str1);printf("str2: %s",str2);pos = mystrstr(str1,str2);if (pos != NULL) {printf("The substring2: %s",pos);} else {printf("No this substring2");}if (pos != NULL) {str1[pos-str1]='0';printf("The substring1: %s",str1);} else {printf("No this substring1");}system("pause");}/*str1:           This is a test,how to find!str2:           testThe substring2:         test,how to find!The substring1:         This is a*/

8 汉字的逆序输出

#include  #include #include  int main(){    char str[20] = "我爰你!";    for (int i = strlen(str)-1; i >=0;)    {        if (str[i] >= 0 && str[i] <= 127) // ASCII 0-127,一个字节存储一个ASCII字符        {            printf("%c", str[i]);            i--;        }        else                         // 两个字节存储一个汉字字符        {            i--;            printf("%c%c", str[i], str[i + 1]);            i--;        }    }        printf("");         system("pause");        return 0;}

-End-

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值