How to check letters in an FString in C++?

Hi.

I want to scan through an FString variable and check the result. If it is a “1” then spawn and object, otherwise, just move along. I’ve got this code below and while I get no code errors, it’s not working as I want. What is happening is that it spawns an object, then nothing, until the last spot, where it spawns another, essentially just the first and last spots. The text to compare is this though, “111111” so it should spawn at every check.

Here’s my code.

for (currentChar = 1; currentChar < newStringLen; currentChar++)
{
	if (newString.Mid(currentChar, currentChar + 1) == TEXT("1"))
		{
			AMyCube* const myCube = World->SpawnActor<AMyCube>(MyCubeClass, FVector(spawnHere.X, spawnHere.Y, spawnHere.Z), GetActorRotation(), SpawnParams); // Spawn it
		}
	

	spawnHere.X += 100;
}

The CURRENTCHAR variable, is the current character point to check. This will FOR/LOOP through the string to check it. If it’s less than NEWSTRINGLEN, a variable I set in the .h file to equal the length of the FString, then run through it.

The IF statement is obviously (I say that, but I may be wrong) where it goes belly up. It checks the MID position of CURRENTCHAR and CURRENTCHAR + 1 of the NEWSTRING variable (that is the string) for the “1”. I’ve tried it with and without the TEXT(), to no avail.

I’m new to Unreal so please be gentle. Can anyone see why it doesn’t work as I want, or why it only spawns the first and last blocks?

Thanks for looking!

Not sure why your code is failing, but the following works perfectly fine for me:

FString stringToCheck = TEXT("000100");

for (int32 i = 0; i < stringToCheck.Len(); i++)
{
	FString currChar = stringToCheck.Mid(i, 1);		

	if (currChar.Equals(TEXT("0")))
	{
		// Don't do stuff
	}
	else if (currChar.Equals(TEXT("1")))
	{
		// Do stuff
	}

}
2 Likes

Second param in MID - “Count”

“newString.Mid(currentChar, 1)” instead of “newString.Mid(currentChar, currentChar + 1)”

Hi,

if you change this line, i think you should be fine

if (newString.Mid(currentChar, 1) == TEXT(“1”))

currentChar + 1 is the end index. But Mid function expects the count of characters from the currentChar position.

Yes it is failing because of

’ currentChar + 1 ’ on line 3 will cause an overflow because (currentChar + 1) will be equal to the string.Len() in the last iteration → which will fail the assert.