兩者都是求字符串的長度,但strlen( )的參數必須是char* ;而 str.length( )是string類對象str調用的成員函數,所以它們用在不同的地方;
char* ch="asdfsafas";
string str="adfadf";
cout<<str.length();
// cout<<strlen(str); 出錯
cout<<strlen(ch);
// cout<<ch.length();出錯
strlen()的定義基本如下:
int strlen( const char *str ) //輸入參數const
{
assert( strt != NULL ); //斷言字符串地址非0
int len;
while( (*str++) != '/0' )
{
len++;
}
return len;
}
assert( strt != NULL ); //斷言字符串地址非0
int len;
while( (*str++) != '/0' )
{
len++;
}
return len;
}
##########################
轉貼:vc在線
類String的構造函數、析構函數和賦值函數,已知類String的原型爲:
class String
{
public:
String(const char *str = NULL); // 普通構造函數
String(const String &other); // 拷貝構造函數
~ String(void); // 析構函數
String & operate =(const String &other); // 賦值函數
private:
char *m_data; // 用於保存字符串
};
{
public:
String(const char *str = NULL); // 普通構造函數
String(const String &other); // 拷貝構造函數
~ String(void); // 析構函數
String & operate =(const String &other); // 賦值函數
private:
char *m_data; // 用於保存字符串
};
//普通構造函數
String::String(const char *str)
{
if(str==NULL)
{
m_data = new char[1]; // 對空字符串自動申請存放結束標誌'/0'的空
//對m_data加NULL 判斷
*m_data = '/0';
}
else
{
int length = strlen(str);
m_data = new char[length+1]; // 若能加 NULL 判斷則更好
strcpy(m_data, str);
}
}
// String的析構函數
String::~String(void)
{
delete [] m_data; // 或delete m_data;
}
//拷貝構造函數
String::String(const String &other) // 輸入參數爲const型
{
int length = strlen(other.m_data);
m_data = new char[length+1]; //對m_data加NULL 判斷
strcpy(m_data, other.m_data);
}
//賦值函數
String & String::operate =(const String &other) // 輸入參數爲const型
{
if(this == &other) //檢查自賦值
return *this;
delete [] m_data; //釋放原有的內存資源
int length = strlen( other.m_data );
m_data = new char[length+1]; //對m_data加NULL 判斷
strcpy( m_data, other.m_data );
return *this; //返回本對象的引用
}
String::String(const char *str)
{
if(str==NULL)
{
m_data = new char[1]; // 對空字符串自動申請存放結束標誌'/0'的空
//對m_data加NULL 判斷
*m_data = '/0';
}
else
{
int length = strlen(str);
m_data = new char[length+1]; // 若能加 NULL 判斷則更好
strcpy(m_data, str);
}
}
// String的析構函數
String::~String(void)
{
delete [] m_data; // 或delete m_data;
}
//拷貝構造函數
String::String(const String &other) // 輸入參數爲const型
{
int length = strlen(other.m_data);
m_data = new char[length+1]; //對m_data加NULL 判斷
strcpy(m_data, other.m_data);
}
//賦值函數
String & String::operate =(const String &other) // 輸入參數爲const型
{
if(this == &other) //檢查自賦值
return *this;
delete [] m_data; //釋放原有的內存資源
int length = strlen( other.m_data );
m_data = new char[length+1]; //對m_data加NULL 判斷
strcpy( m_data, other.m_data );
return *this; //返回本對象的引用
}