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;

}

 

posted @ 2016-01-08 09:43  银月星  阅读(3048)  评论(0编辑  收藏  举报