0

I appreciate the time you spend reading this :)

Basically im trying to run an if command if a string is greater than so many characters.

So im running a bunch of line.conatins to filter out what I dont want, but I also want to add a character count, so if the line has less than 30 characters it will filter it out.

So basically, im looking for something like this in C# visual studio 2008

if (line.contains > 30 characters) 
{
    Run code...
}

Im not to sure of the right syntax to use, and google hasnt been very forthcoming.

I appreciate any help. Thanks, Jason

Wow thanks for the fast response guys, but with lots of trial and error i came up with this

int num_count = line.Length;
                    if (num_count > 30) { }

seems to work

4

3 回答 3

3
string data = "fff"

if (data.Length > 30)
{
 // MAgic stuff here
}
于 2013-10-22T02:40:42.520 回答
0

This should do what you want.

            string str = "yourstring";
            int i = str.Length;

Also try to post code next time you ask something it helps a lot when determining exactly what you want.

于 2013-10-22T02:41:48.623 回答
0

The short, but näive, answer is to use this property:

String.Length

You might want to think about what you mean by character. .NET's String class is a counted sequence of UTF-16 code units, which it types as Char. There are either one or two UTF-16 code units in a Unicode code point, and it's easy to calculate as you step through each Char. Where two code units are used, they are called the low and high surrogates.

But also note that Unicode can represent diacritics and such as separate code points. You might want to exclude them in your count.

Putting them together:

using System.Linq;
...
var test = "na\u0308ive"; // want to count ä as one character
var categoriesNotToCount = new []
{ 
    UnicodeCategory.EnclosingMark,
    UnicodeCategory.NonSpacingMark, 
    UnicodeCategory.SpacingCombiningMark 
};
var length = test
    .Count(c => 
        !categoriesNotToCount.Contains(Char.GetUnicodeCategory(c)) // we just happen to know that all the code points in categoriesNotToCount are representable by one UTF-16 code unit
        & !Char.IsHighSurrogate(c) // don't count the high surrogate because we're already counting the low surrogate 
    );

It all comes down to what you're after. If it's the number of UTF-16 code units you want then, for sure, String.Length is your answer.

于 2013-10-22T03:45:34.183 回答