一個不錯的字串轉碼解碼函數(自寫),字串函數
function isString(variable) { return Object.prototype.toString.call(variable).indexOf('String') != -1;}function isNumeric(variable) { return !isNaN(parseFloat(variable)) && isFinite(variable);}function stringEncode(string) { string = isString(string) || isNumeric(string) ? String(string) : ''; var code, i = 0, code_string = '', len = string.length; while(i < string.length) { code = string.charCodeAt(i); code_string += '' + String(code).length + code; i++; } return code_string;}function stringDecode(code) { var i = 0, code_len, decode_string = ''; code = String(code); while(i < code.length) { code_len = +code.charAt(i); i++; decode_string += String.fromCharCode(+code.substr(i, code_len)); i += code_len; } return decode_string;}
寫一個函數把字串2拷貝到字串1中,不準用strcpy函數;
附贈strlen( char *p )和strcmp( char *p1 , char *p2 ) :]
(1)字串長度函數:
int strlen( char *p )
{
int i=0;
while( p[i]!='\0' ){
i++;
}
return i;
}
(2)字串複製函數:
//將p2所指的內容全部賦給p1
void strcpy( char *p1 , char *p2 )
{
int i=0;
while( p2[i]!='\0'){
p1[i]=p2[i];
i++;
}
p1[i]='\0';
}
(3)字串比較函數:
int strcmp( char *p1 , char *p2 )
{
int i=0;
while( p1[i]!='\0' && p2[i]!='\0'){
if( p1[i]-p2[i] )
return p1[i]-p2[i];
i++;
}
return strlen(p1)-strlen(p2);
}
(4)最後,提供一個主函數供你測試一下,並附測試案例及預期輸出結果 :]
int main()
{
char *p1 , *p2;
p1=new char[1000];
p2=new char[1000];
while( cin>>p1>>p2 ){
cout<<strlen(p1)<<endl;
cout<<strlen(p2)<<endl;
cout<<strcmp(p1,p2)<<endl;
strcpy(p1,p2);
cout<<"after copying p1 becomes "
<<p1<<endl;
}
return 0;
}
/*
helloWorld
myGirl
10
6
-5
after copying p1 becomes myGirl
abcdef
bcdefg
6
6
-1
after copying p1 becomes bcdefg
abcdefg
......餘下全文>>
編寫一個函數將一個整數轉換成數字字串 C語言
#include <stdio.h>#define N 10
//編寫一個函數將一個整數的各位元提取出來,並將其轉換成數字字串,
//在主函數中輸出該字串,不用指標,用簡單點的C語言。
int main()
{
int number_int,i,str_len;
char number_str[N],swap_temp;
scanf("%d",&number_int);
i=0;
while(number_int)
{
number_str[i]=number_int%10+48;
number_int/=10;
i++;
}
number_str[i]='\0';
str_len=i-1;
for(i=0;i<=str_len/2;i++)
{
swap_temp=number_str[i];
number_str[i]=number_str[str_len-i];
number_str[str_len-i]=swap_temp;
}
printf("%s\n",number_str);
}