计算字符串中的单词数量 [英] Count the no of words in a string

查看:93
本文介绍了计算字符串中的单词数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我需要计算一个字符串中的单词数,并在不同的行中输入每个单词。



示例:



单词 - 做或死



预期输出:

计数3



table



do



die



我的尝试:





我需要计算一个字符串中的单词数,并在不同的行中输入每个单词。



示例:



单词 - 做或死



预期输出:

数3



桌子



do



die

解决方案

基本上,不要 - SQL字符串处理最好是穷人。

你可以做到,但它很笨拙,你会有工作了一下。这可能有所帮助:将列中的逗号分隔数据转换为行选择 [ ^ ] - 或至少给你一个想法。




这是一个简洁的解决方案......我的想法是用整个单词分割文本,应该很容易得到没有单词



从链接复制代码: c# - 如何分割字符串保留整个单词? - 堆栈溢出 [ ^ ]



公共静态类ExtensionMethods 
{
public static string [ ] Wrap(此字符串文本,int max)
{
var charCount = 0;
var lines = text.Split(new [] {''},StringSplitOptions.RemoveEmptyEntries);
返回lines.GroupBy(w =>(charCount + =(((charCount%max)+ w.Length + 1> = max)
?max - (charCount%max):0) + w.Length + 1)/ max)
。选择(g => string.Join(,g.ToArray()))
.ToArray();
}
}


我完全同意上面的OriginalGriff ...这是一个简单的C#RegEx版本,可以解决问题。

  var  WordCount = Regex.Matches(text, @   \ b [A-Za-z0-9] + \ b)。计数; 


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

解决方案

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.


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();
    }
}


I agree totally with OriginalGriff above... Here is a simple RegEx version for C# that does the trick.

var WordCount = Regex.Matches(text, @"\b[A-Za-z0-9]+\b").Count;


这篇关于计算字符串中的单词数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆