Skip to content

Instantly share code, notes, and snippets.

@r1235613
Last active April 12, 2017 06:09
Show Gist options
  • Save r1235613/e3a4b8d128eb666ac53ac59fbaa1fa78 to your computer and use it in GitHub Desktop.
Save r1235613/e3a4b8d128eb666ac53ac59fbaa1fa78 to your computer and use it in GitHub Desktop.
//str_len
#include <stdio.h>
int strlen(char*s){
int length=0;
while(s[length])
++length;
return length;
}
int main(){
char *s="Hello 0123!";
printf("字串'%s'的長度為'%d'\n", s, strlen(s));
return 0;
}
bool strneq(char *p, char *q, int n){
int i=0;
while( (*p||*q) && i++<n ){
if(*p!=*q)
return false;
p++;
q++;
}
return true;
}
int main() {
char s1[]="AB";
char s2[]={'A', 0, 'A', 'C', 0};
bool cond=strneq(s1, s2, 2);
cond=strneq(s1, s2+2, 1);
return 0;
}
bool streq(char *p, char *q){
while(*p||*q)
if(*p++!=*q++)
return false;
return true;
}
int main() {
char s1[]="AB";
char s2[]={'A', 0, 'A', 'B', 0};
bool cond=streq(s1, s2);
cond=streq(s1, s2);
streq(s1, s2+2);
return 0;
}
bool strneq(char *p, char *q, int n){
int i=0;
while( *p||*q && i++<n ) // short-cut evaluation if(*p++!=*q++)
return false;
return true;
}
int main() {
char s1[]="AB";
char s2[]={'A', 0, 'A', 'C', 0};
bool cond=strneq(s1, s2, 1); cond=strneq(s1, s2+2, 1);
return 0;
}
// #'0' char
#include <stdio.h>
int char_count(char*str, char ch){
int count=0;
for(int i=0; str[i]!=0; ++i)
if(str[i]==ch)
++count;
return count;
}
int main(){
char *s="Hello 0123!";
printf("'%s'裡面有'%d'個'%c'字元\n", s, char_count(s,'0'), '0');
return 0;
}
//#digit
#include <stdio.h>
int digit_count(char*str){
int count=0;
for(int i=0; str[i]; ++i)
if(str[i]>='0' && str[i]<='9')
++count;
return count;
}
int main(){
char *s="Hello 0123!";
printf("'%s'裡有%d個數字字元\n",` s, digit_count(s));
return 0;
}
@nicolechang002
Copy link

nicolechang002 commented Apr 12, 2017

``
//#digit

#include <stdio.h>
int digit_count(char*str){
int count=0;
for(int i=0; str[i]; ++i)
if(str[i]>='0' && str[i]<='9')
++count;
return count;
}
int main(){
char *s="Hello 0123!";
printf("'%s'裡有%d個數字字元\n",` s, digit_count(s)); return 0;
}
``

@nicolechang002
Copy link

``
// all are digit

#include <stdio.h>
int are_all_digit(char*str){
for(int i=0; str[i]; ++i)
if(! (str[i]>='0' && str[i]<='9'))
return 0;
return *str?1:0;

}
int main(){
char *s="Hello 0123!";
printf("'%s'裡全部都是字元? %D\n",s,are_all_digit(s));
return 0;
}

``

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment