VC++ MFC 如何實現在編輯框中輸出具有換行功能的文段 01


很久不來寫東西了,昨天睡覺前寫個小工具,突然,這玩意不會換行怎么整...

首先是第一步,獲取字符串的長度,轉載自白喬的文章。

----------------------------------------------------------------------------------------------------------------------------------------------------------

4.5.8  字符串的長度

字符串的長度通常是指字符串中包含字符的數目,但有的時候人們需要的是字符串所占字節的數目。常見的獲取字符串長度的方法包括如下幾種。

1.使用sizeof獲取字符串長度

sizeof的含義很明確,它用以獲取字符數組的字節數(當然包括結束符0)。對於ANSI字符串和UNICODE字符串,

形式如下: 1.sizeof(cs)/sizeof(char) 

               2.sizeof(ws)/sizeof(wchar_t)

可以采用類似的方式,獲取到其字符的數目。如果遇到MBCS,如"中文ABC",很顯然,這種辦法就無法奏效了,因為sizeof()並不知道哪個char是半個字符。

 

2.使用strlen()獲取字符串長度

strlen()及wcslen()是標准C++定義的函數,它們分別獲取ASCII字符串及寬字符串的長度,

如: 1.size_t strlen( const char *string ); 

       2.size_t wcslen( const wchar_t *string );

strlen()與wcslen()采取0作為字符串的結束符,並返回不包括0在內的字符數目。

 

3.使用CString::GetLength()獲取字符串長度

CStringT繼承於CSimpleStringT類,該類具有函數:

  1.int GetLength( ) const throw( );

GetLength()返回字符而非字節的數目。

比如:CStringW中,"中文ABC"的GetLength()會返回5,而非10。

那么對於MBCS呢?同樣,它也只能將一個字節當做一個字符,CStringA表示的"中文ABC"的GetLength()則會返回7。

//漢字占2個字節,英文字母占用1個字節。

 

4.使用std::string::size()獲取字符串長度

basic_string同樣具有獲取大小的函數:

1.size_type length( ) const; 

2.size_type size( ) const;

length()和size()的功能完全一樣,它們僅僅返回字符而非字節的個數。如果遇到MCBS,它的表現和CStringA::GetLength()一樣。

 

5.使用_bstr_t::length()獲取字符串長度

_bstr_t類的length()方法也許是獲取字符數目的最佳方案,嚴格意義來講,_bstr_t還稱不上一個完善的字符串類,它主要提供了對BSTR類型的封裝,基本上沒幾個字符串操作的函數。

不過,_bstr_t 提供了length()函數: 1.unsigned int length ( ) const throw( ); 

該函數返回字符的數目。值得稱道的是,對於MBCS字符串,它會返回真正的字符數目。

現在動手

編寫如下程序,體驗獲取字符串長度的各種方法。

【程序 4-8】各種獲取字符串長度的方法 1.01 

#include "stdafx.h"

#include "string" 

#include "comutil.h"

#pragma comment( lib, "comsuppw.lib" )

using namespace std; 

int main() 

{char s1[] = "中文ABC"; 

wchar_t s2[] = L"中文ABC";

//使用sizeof獲取字符串長度 

printf("sizeof s1: %d/r/n", sizeof(s1)); 

printf("sizeof s2: %d/r/n", sizeof(s2)); 


//使用strlen獲取字符串長度

printf("strlen(s1): %d/r/n", strlen(s1));

printf("wcslen(s2): %d/r/n", wcslen(s2)); 

//使用CString::GetLength()獲取字符串長度 

CStringA sa = s1; 

CStringW sw = s2;

printf("sa.GetLength(): %d/r/n", sa.GetLength());

printf("sw.GetLength(): %d/r/n", sw.GetLength()); 

//使用string::size()獲取字符串長度

string ss1 = s1; 

wstring ss2 = s2; 

printf("ss1.size(): %d/r/n", ss1.size()); 

printf("ss2.size(): %d/r/n", ss2.size()); 

//使用_bstr_t::length()獲取字符串長度

_bstr_t bs1(s1); 

_bstr_t bs2(s2);

printf("bs1.length(): %d/r/n", bs1.length());

printf("bs2.length(): %d/r/n", bs2.length()); 

return 0;

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM