Click here to Skip to main content
15,884,177 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
hi,
I need to count the number of words in a string and enter each word in different rows.

Example:

Words - do or die

expected Output:
Count 3

table

do
or
die

What I have tried:

hi,
I need to count the number of words in a string and enter each word in different rows.

Example:

Words - do or die

expected Output:
Count 3

table

do
or
die
Posted
Updated 15-Jul-17 11:59am
Comments
Patrice T 15-Jul-17 14:49pm    
What is the question ?
What have you done ? problem ?
Bryian Tan 15-Jul-17 15:18pm    
look like homework assignment :)
Patrice T 15-Jul-17 15:47pm    
to me too :)
PIEBALDconsult 15-Jul-17 15:42pm    
Avoid all string manipulation in SQL.

Basically, don't - SQL string handling is at best poor.
You can do it, but it's clumsy, and you're going to have to work a bit. This may help: Converting comma separated data in a column to rows for selection[^] - or at least give you an idea.
 
Share this answer
 
Hi,
Here's a neat solution...the idea is to split text by whole words and should be quite easy to get no of words

Copying code from link: c# - How to split string preserving whole words? - Stack Overflow[^]

public static class ExtensionMethods
{
    public static string[] Wrap(this string text, int max)
    {
        var charCount = 0;
        var lines = text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        return lines.GroupBy(w => (charCount += (((charCount % max) + w.Length + 1 >= max) 
                        ? max - (charCount % max) : 0) + w.Length + 1) / max)
                    .Select(g => string.Join(" ", g.ToArray()))
                    .ToArray();
    }
}
 
Share this answer
 
I agree totally with OriginalGriff above... Here is a simple RegEx version for C# that does the trick.
C#
var WordCount = Regex.Matches(text, @"\b[A-Za-z0-9]+\b").Count;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900