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

  • Post author:
  • Post category:其他


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

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-