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.
^  ^                ^^         ^                    ^