C++/CLI学习入门(四):字符串(转)

C++/CLI字符串(Unicode字符组成的字符串)是指在System命名空间中定义的String类,即由System:Char类型的字符序列组成的字符串。它包含大量强大的功能,使得字符串的处理非常容易。创建一个String对象的方法如下例所示:

System::String^ saying = L"Many hands make light work.";

跟踪句柄saying用于访问String类对象。该对象的字符为宽字符,因为采用了前缀 “L”,如果省略“L”,该字符串由8位的字符组成,编译器将确保将其转换成宽字符。

访问字符串内字符可以像访问数组元素一样,使用索引来访问,首字符的索引为0。这种方法只能用于读取字符串内字符,但不能用于修改字符串的内容。

Console::WriteLine("The third character in the string is {0}", saying[2]);

利用Length属性,可以获取字符串内字符的数量(长度)。

Console::WriteLine("The saying has {0} charactors.", saying->Length);一、连接字符串

利用 “+”可以连接字符串,形成新的字符串。执行下面的例子之后,name3将包含字符串 “Beth and Betty”。

String^ name1 = L"Beth";
String^ name2 = L"Betty";
String^ name3 = name1+L" and "+name2;

“+”还可以用来连接字符串与数值、bool值等非字符串变量,在连接之前,这些变量将自动的转换成字符串。

String^ str = L"Value: ";
String^ str1 = str + 2.5; // str1 is "Value: 2.5"
String^ str2 = str + 25; // str2 is "Value: 25"
String^ str3 = str + true; // str3 is "Value: True"

“+”还可以用来连接字符串与字符,但要注意,结果字符串的形式取决于字符的类型。这是因为char类型的字符被视为数值,wchar_t与String对象的字符具有相同的类型(Char类型)。

char ch = 'Z';
wchar_t wch = 'Z';
String^ str4 = str + ch; // str4 is "Value: 90"
String^ str5 = str + wch; // str5 is "Value: Z"

String类型定义了Join()函数,用于将数组中的多个字符串连接成一个字符串,数组元素之间用分隔符隔开,如

array<String^>^ names = {"Jill", "Ted", "Mary", "Eve", "Bill"};
String^ seperator = " and ";
String^ joined = String::Join(seperator, names); // joined is "Jill and Ted and Mary and Eve and Bill"

特别注意:String对象是固定不变的,一旦创建完毕后就不能再被修改了。这意味着所有的字符串操作都是在创建新的字符串。

下面的例子将整数数组内的元素按列整齐地输出。

- - - - - - - - - - - - - - - - <<== 华丽的分割线 ::开始==>> [Ex4_17.cpp] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -// Ex4_17.cpp : main project file.
#include "stdafx.h"

using namespace System;

int main(array<System::String ^> ^args)
{
array<int>^ values = { 2, 456, 23, -46, 34211, 456, 5609, 112098, 234,
-76504, 341, 6788, -909121, 99, 10 };
String^ formatStr1 = "{0, ";
String^ formatStr2 = "}";
String^ number;

int maxLength = 0;
for each(int value in values)
{
number = ""+value;
if(maxLength<number->Length)
maxLength = number->Length;
}

String^ format = formatStr1+(maxLength+1)+formatStr2;

int numberPerLine = 3;
for(int i=0; i<values->Length; i++)
{
Console::Write(format, values[i]);
if((i+1)%numberPerLine == 0)
Console::WriteLine();
}
}- - - - - - - - - - - - - - - - <<== 华丽的分割线 ::结束==>> [Ex4_17.cpp] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

输出为

2 456 23
-46 34211 456
5609 112098 234
-76504 341 6788
-909121 99 10二、修改字符串

Trim()函数用于删除字符串头部和尾部的空格。不带参数调用该函数将删除字符串头、尾部的全部空格并返回一新字符串。

String^ str = {" Handsome is as handsome does... "};
String^ newStr = str->Trim();

也可传递给Trim()函数字符数组作为参数,字符串将从头部和尾部开始删除数组中的字符。如果字符出现在字符串中间,则不会被删除。

String^ toBeTrimed = L"wool wool sheep sheep wool wool wool";
array<wchar_t>^ notWanted = {L'w', L'o', L'l', L' ' };
Console::WriteLine(toBeTrimed->Trim(notWanted));

上面的语句将输出
sheep sheep

如果在上面的语句中没有加前缀”L“,则字符为char类型,对应于System::SByte类型。不过编译器将自动地将其转换成wchar_t类型(即System::Char类型)。

Trim()函数也支持直接输入要删除的字符列表,下面的语句将产生同样的输出

Console::WriteLine(toBeTrimed->Trim(L'w', L'o', L'l', L' '));

如果仅仅想要删除头部或者尾部中的一端,可以使用TrimStart或者TrimEnd函数。

如果要在字符串的一端填充空格或其它字符(这一般用于以固定宽度靠左或靠右对齐输出文本),可使用PadLeft()和PadRight()函数。如果字符串长度大于指定的长度参数,则返回字符串为长度等于原来字符串的新字符串。

String^ value = L"3.142";
String^ leftPadded = value->PadLeft(10); // Result is " 3.142"
String^ rightPadded = value->PadRight(10); // Result is "3.142 "
String^ leftPadded2 = value->PadLeft(10, L'*'); // Result is "*****3.142"
String^ rightPadded2= value->PadRight(10,L'#'); // Result is "3.142#####"

如果需要将字符串转换成大写或小写,可使用ToUpper()或ToLower函数。

String^ proverb = L"Many hands make light work."
String^ upper = proverb->ToUpper(); // Result is "MANY HANDS MAKE LIGHT WORK."

如果需要在字符串中间插入一个字符串,可使用Insert()函数,第一个参数指定起始位置的索引,第二个参数指定要插入的字符串。

String^ proverb = L"Many hands light work.";
String^ newProverb = proverb->Insert(5, "deck ");

结果是

Many deck hands make light work.

如果要用另一个字符替换字符串中指定的字符,或者用另一个子串替换字符串中给定的子串,可使用Replace()函数。

String^ proverb = L"Many hands make light work."
Console::WriteLine(proverb->Replace(L' ', L'*');
Console::WriteLine(proverb->Replace(L"Many hands", L"Press switch");

输出为

Many*hands*make*light*work.
Pressing switch make light work.三、搜索字符串

如果需要测试字符串是否以给定的子串开始或结束,可使用StartWith()或EndWith()函数。要寻找的子串句柄作为参数传递给函数,返回bool值。

String^ snetence = L"Hide, the cow's outside.";
if(sentence->StartWith(L"Hide"))
Console::WriteLine("The sentence starts with 'Hide'.");

IndexOf()函数用于返回给定字符或子串在字符串中找到的第一个实例索引,如果未找到,则返回-1。

String^ sentence = L"Hide, the cow's outside.";
int ePosition = sentence->IndexOf(L'e'); // Return 3
int thePosition = sentence->IndexOf(L"the"); // Retuen 6

也可以指定IndexOf搜索的起始索引,这一般用于遍历整个字符串找出所有的实例,如下面的例子:

int index = 0;
int count = 0;
while((index=words->IndexOf(word, index))>=0)
{
index += word->Length;
count++;
}
Console::WriteLine(L"'{0}' was found {1} times in: {2}", word, count, words);

LastIndexOf()函数类似于IndexOf()函数,不过它用于从字符串尾部或指定索引位置开始,倒着向头部搜索。注意:如果从尾部开始的索引值是words->Lenght-1。

如果要搜索一个字符串数组中任意元素出现在字符串中的位置,可以使用IndexOfAny()函数。同样,它也有倒序搜索的版本。 下面的例子说明了IndexOfAny()的用法。下面的例子用于搜索字符串中的标点符号

- - - - - - - - - - - - - - - - <<== 华丽的分割线 ::开始==>> [Ex4_18.CPP] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -// Ex4_18.cpp : main project file.
#include "stdafx.h"

using namespace System;

int main(array<System::String ^> ^args)
{
array<wchar_t>^ punctuation = {L'"', L'\'', L'.', L',', L':',L'!', L'?'};
String^ sentence = L"\"It's chilly in here\", the boy 's mother said coldly.";

array<wchar_t>^ indicators = gcnew array<wchar_t>(sentence->Length){L' '};

int index = 0;
int count = 0;
while((index=sentence->IndexOfAny(punctuation, index))>=0)
{
indicators[index] = L'^';
++index;
++count;
}
Console::WriteLine(L"There are {0} punctuation charactors in the string:", count);
Console::WriteLine(L"\n{0}\n{1}", sentence, gcnew String(indicators));
return 0;
}- - - - - - - - - - - - - - - - <<== 华丽的分割线 ::结束==>> [Ex4_18.cpp] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 输出为There are 6 punctuation charactors in the string:
"It's chilly in here", the boy 's mother said coldly.
^ ^ ^^ ^ ^
<script type="text/javascript" id="wumiiRelatedItems"> </script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值