Visual C++ String Array

String type

You want to use a string array in your Visual C++ program, based on the .NET Framework types. By employing the array and gcnew keywords, you can allocate an array upon the managed heap.

Example

Note

To begin, this program defines the main method and it uses the array<String ^> syntax as the type of the array. To allocate the array, call the gcnew method; this is equivalent to the new operator in the C# language. Next, you can directly assign string literals into the values array.

This Visual C++ example program creates a string array. It shows the syntax.

Program that creates string array [C++]

#include "stdafx.h"

using namespace System;

int main()
{
    // Create array of three strings.
    array<String ^> ^ values = gcnew array<String ^>(3);
    values[0] = "cat";
    values[1] = "two";
    values[2] = "three";

    // Write length.
    Console::WriteLine("Length: {0}", values->Length);

    // Print all values.
    Console::WriteLine("Values: {0}", String::Join(",", values));

    return 0;
}

Output

Length: 3
Values: cat,two,three

Using Length and Join. The program also demonstrates how you can use the Length property and the String::Join method. These are available anywhere you have an array or include the System namespace. The String::Join method puts a comma delimiter character between all the elements in the output string.

Managed C++

Programming tip

The code that Visual Studio compiles this program to is represented in the intermediate language, which is the same as the C# language or VB.NET language compile to. The generated code may actually be somewhat less efficient because the array variable is initially assigned to null; don't expect managed C++ to be faster.

Summary

Here, we wrote a program that allocated a string array in the Visual C++ language with the gcnew keyword. In programs where you need to use managed C++, equivalent C# code can be modified to work with some syntactic fixes.

Dot Net Perls
.NET