Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count length of word without using Inbuilt functions

Tags:

string

c#

This is a question I have come across and failed

Suppose say

string str = "wordcounter";

One can easily find the Length using str.Length

However, is it possible in C# to get the number of letters, without using any inbuilt functions like Length, SubStr etc

like image 797
Binil Avatar asked Sep 20 '11 12:09

Binil


People also ask

How do you find the length of a string without an inbuilt function?

Calculate Length of String without Using strlen() Function Here, using a for loop, we have iterated over characters of the string from i = 0 to until '\0' (null character) is encountered. In each iteration, the value of i is increased by 1. When the loop ends, the length of the string will be stored in the i variable.

How do you find the length without using the LEN function?

How to implement without using len(): Approach: Take input and pass the string/list into a function which return its length. Initialize a count variable to 0, this count variable count character in the string.


1 Answers

you could write a loop and increment a counter inside this loop:

int numberOfLetters = 0;
foreach (var c in str)
{
    numberOfLetters++;
}
// at this stage numberOfLetters will contain the number of letters 
// that the string contains

there is also another way:

int numberOfLetters = str.ToCharArray().Length;

there is also another, even crazier way using the SysStringByteLen function which operates on a BSTR. Strings in .NET are layed out in memory by using a 4 byte integer containing the length of the string followed by that many 2 byte UTF-16 characters representing each character. This is similar to how BSTRs are stored. So:

class Program
{
    [DllImport("oleaut32.dll")]
    static extern uint SysStringByteLen(IntPtr bstr);

    static void Main()
    {
        string str = "wordcounter";
        var bstr = Marshal.StringToBSTR(str);

        // divide by 2 because the SysStringByteLen function returns 
        // number of bytes and each character takes 2 bytes (UTF-16)
        var numberOfLetters = SysStringByteLen(bstr) / 2; 
        Console.WriteLine(numberOfLetters);
    }
}

Obviously doing something like this instead of using the built-in Length function should never be done in any real production code and the code shown here should not be taken seriously.

like image 81
Darin Dimitrov Avatar answered Nov 10 '22 00:11

Darin Dimitrov