How to count the number of strings available in a sentence

i want to count the words inside a string value or sentence. and take the last two words and put it into a variable. is there any way to achieve this?

Hi @Tammy1998,
Yes you can split the sentence into array (by spaces) using “.split(” “c)” and then use count method and take the last two words and store them into variables using assign activity.

Hope it helps :slight_smile:


Easy to achieve with string split and then finding the last two elements and concatinating them.

strArrayValues(strArrayValues.Length-2)+" " + strArrayValues(strArrayValues.Length-1)

You should consider edge cases and handle them accordingly if the string is empty or not enough elements in array etc.


this works but it gives me an error…

Assign: Index was outside the bounds of the array.

is there any way to solve this?

Hope these steps would help you resolve this
If the string input is tired in a variable named strinput
Then in assign activity

arr_string = Split(Strinput.ToString,” “)

Where arr_string is a variable of type array of string

—now use a assign activity like this
int_count = arr_string.Count

Where int_count is a variable of type int32

—and another assign activity like this to get the last element
Str_output1 = arr_string.Last().ToString

And to get the previous last
Str_output2 = arr_string(int_count-2).ToString

Cheers @Tammy1998


Try this,

texty.ToString.Split(" "c).Count.ToString

1 Like

That is because you may have string that is empty or string with only one word in it. In those cases your string.split gives you less number of elements then 2.

What you need is a if condition to check if string split produced more than 2 array elements.

Add an if condition before concatinating to check

thank you so much for your help… all of your solutions helped me to solve the problem. thank you.