一波C說話字符數組適用技能集錦。本站提示廣大學習愛好者:(一波C說話字符數組適用技能集錦)文章只能為提供參考,不一定能成為您想要的結果。以下是一波C說話字符數組適用技能集錦正文
字符數組倒序
#include <stdio.h> void daoxu(char str[]){ int i; char temp; for(i = 0; i < strlen(str) / 2 ; i ++){ temp = str[i]; str[i] = str[strlen(str) - i-1]; str[strlen(str) - i-1] = temp; } }
單詞計數
int wordCount(char str[]){ int i; int count = 0; int word = 0; for (i = 0 ; str[i] != '\0' ; i ++) { if (str[i] == ' ') { word = 0; }else if (word == 0) { word = 1; count ++; } } return count; }
字符年夜寫轉小寫
void mylwr(char str[]){ int i; for (i = 0 ; str[i] != '\0' ; i ++) { if (str[i] >= 'A' && str[i] <= 'Z') { str[i] += 'a' - 'A'; } } }
字符小寫轉年夜寫
void myupr(char str[]){ int i; for (i = 0 ; str[i] != '\0' ; i ++) { if (str[i] >= 'a' && str[i] <= 'z') { str[i] -= 'a' - 'A'; } } }
字符數組盤算字符串長度
int mylen(char str[]){ int len; for (len = 0 ; str[len] != '\0' ; len ++); return len; }
字符串聯接
void mycat(char str1[],char str2[]){ int i,j; for (i = 0 ; str1[i] != '\0' ;i++); for (j = 0 ; str2[j] != '\0' ; j ++) { str1[i + j] = str2[j]; } str1[i + j] = '\0'; }
指定長度串接
void myncat(char str1[],char str2[], int len){ int i,j; for(i = 0; str1[i] != '\0'; i++); for (j = 0; j < len; j++) { str1[i + j] = str2[j]; } str1[i + j] = '\0'; }
字符數組拷貝
void mycpy(char dst[],char src[]){ int i = 0; do { dst[i] = src[i]; } while (src[i++] != '\0'); }
字符數組指定長度拷貝
void myncpy(char dst[],char src[], int len){ int i; for (i = 0; i < len; i++) { dst[i] = src[i]; } dst[i] = '\0'; }
找出句子中最長的單詞
void longest(char dst[],char src[]){ int i = 0,j; int count =0; int max = -1; do { if (src[i] ==' ' || src[i] == '\0') { if (count > max) { max = count; for (j = 0; j < count; j++) { dst[j] = src[i - count + j]; } dst[j] = '\0'; } count = 0; }else{ count++; } } while (src[i++] != '\0'); }
從字符串中提取整形數字
#include <stdio.h> int getint(char str[], int a[]){//從字符串中提取數字並放在數組中 int i = 0; int w = 0; int c = 0; int j, k; do { if (str[i] > '0' && str[i] <= '9') { w++; }else if (w) { j = 0; for (k = w; k > 0; k--) { j *= 10; j += str[i - k] - '0'; } w = 0; a[c] = j; c++; } } while (str[i++] != '\0'); return c; } void main(){ char str[100]; int a[100]; int i, j; gets(str); i = getint(str,a); for (j = 0; j < i; j++) { printf("%d ",a[j]); } }
整形、字符數組型轉換
#include <stdio.h> #include <stdlib.h> int sumof1(int x)//求一個數轉換成二進制今後1的個數 { int countx = 0; while(x) { countx ++; x &= x-1; //每位與一次x - 1;就可以消失落最初一個1 } return countx; } void main(){ char c[10]; int i = 999; itoa(i, c, 10);//以10進制轉換成字符數組 puts(c); itoa(i, c, 16);//以16進制轉換成字符數組 printf("0x%s\n", c); itoa(i, c, 8);//以8進制轉換成字符數組 printf("0%s\n", c); itoa(i, c, 2);//以2進制轉換成字符數組 puts(c); i = atoi(c);//再將字符串轉成整形 printf("%d\n", i); printf("%d\n", sumof1(i));//以2進制表現時1的個數 }