Count no. of words in a string

Hi everyone,

How to count no. of words in a string.

Ex,
XYZ ABC =2
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,}"," ")
2 Likes

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

1 Like

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

1 Like

Thanks @ppr

@ShekharRPA

Check below for your reference

image

Hope this will help you

Thanks

2 Likes

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.