一個不錯的字串轉碼解碼函數(自寫),字串函數

來源:互聯網
上載者:User

一個不錯的字串轉碼解碼函數(自寫),字串函數

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);

}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.