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

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

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

int compl(int a, int b){if(a^b)return 1;elsereturn 0; // 两个相等的数字,XOR运算符返回0}
2cae6a32dc219e94269695043cff252e.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;}
59985589535d159f29aa15d08ba16fc8.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;}
e9f52d64e4330ce46a589a7196d7c197.png

6 生成随机字符串

365e9faf7050235048203479123eac4a.png
#include #include #include using namespace std;string randStr(int n, int m){string str;srand((unsigned)time(NULL));for(int i=0;i
9203ac678e32946d51d1418ec812a95e.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-

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值