Count no. of words in a string

Hi everyone,

How to count no. of words in a string.

String.split(" "c).count.tostring this working for having one space case.

But if data is like,
XYZ ABC PQR DEF=9, Which is wrong
If failing for case where we have more than a space.

Hi @ShekharRPA ,

We can first Remove the Extra Spaces with one space and then Perform the Count.

The Below Expression should Return the String with only one Space :

System.Text.RegularExpressions.Regex.Replace(yourStringVar,"\s{2,}"," ")
1 Like

have a check on YourStringVar.split({" "},StringSplitOptions.RemoveEmptyEntries)
or go for a regex like

1 Like

Better way to convert multiple spaces with single, Thanks @supermanPunch

1 Like

Thanks @ppr


Check below for your reference


Hope this will help you


1 Like

This will fail in case of spaces more than 2. The one sample shared by @supermanPunch is the better approach.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.