官术网_书友最值得收藏!

UE4 – making an FString from FStrings and other variables

When coding in UE4, you often want to construct a string from variables. This is pretty easy using the FString::Printf or FString::Format functions.

Getting ready

For this, you should have an existing project into which you can enter some UE4 C++ code. Putting variables into a string is possible via printing. It may be counterintuitive to print into a string, but you can't just concatenate variables together, and hope that they will automatically convert to string, as in some languages such as JavaScript.

How to do it…

  1. Using FString::Printf():
    1. Consider the variables you'd like printed into your string.
    2. Open and take a look at a reference page of the printf format specifiers, such as http://en.cppreference.com/w/cpp/io/c/fprintf.
    3. Try code such as the following:
      FString name = "Tim";
      int32 mana = 450;
      FString string = FString::Printf( TEXT( "Name = %s Mana = %d" ), *name, mana );

    Notice how the preceding code block uses the format specifiers precisely as the traditional printf function does. In the preceding example, we used %s to place a string in the formatted string, and %d to place an integer in the formatted string. Different format specifiers exist for different types of variables, and you should look them up on a site such as cppreference.com.

  2. Using FString::Format(). Write code in the following form:
    FString name = "Tim";
    int32 mana = 450;
    TArray< FStringFormatArg > args;
    args.Add( FStringFormatArg( name ) );
    args.Add( FStringFormatArg( mana ) );
    FString string = FString::Format( TEXT( "Name = {0} Mana = {1}" ), args );
    UE_LOG( LogTemp, Warning, TEXT( "Your string: %s" ), *string );

    With FString::Format(), instead of using correct format specifiers, we use simple integers and a TArray of FStringFormatArg instead. The FstringFormatArg helps FString::Format() deduce the type of variable to put in the string.

主站蜘蛛池模板: 石楼县| 福贡县| 高密市| 太原市| 小金县| 桦川县| 淳化县| 双鸭山市| 大方县| 剑川县| 顺义区| 无为县| 沭阳县| 新乡市| 金门县| 富顺县| 龙里县| 黑山县| 齐齐哈尔市| 华安县| 河间市| 西贡区| 定结县| 襄城县| 陇南市| 南郑县| 镇康县| 长沙县| 柘荣县| 双辽市| 贺兰县| 湖南省| 霍城县| 江永县| 方山县| 平乐县| 平乡县| 札达县| 北票市| 张北县| 缙云县|