Binil
Binil

Reputation: 6583

Count length of word without using Inbuilt functions

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

Upvotes: 5

Views: 27609

Answers (9)

kaushik
kaushik

Reputation: 70

namespace ConsoleApplication {  
class Program {  
    static void Main(string[] args) {  
        string testString = "testing";  
        int x = 0;  
        foreach(char c in testString) {  
            x++;  
        }  
        Console.WriteLine("\nLength Of String:{0}", (x));  
        Console.Read();  
    }  
}  

Upvotes: -1

Awais
Awais

Reputation: 1

class Program
{
    static void Main(string[] args)
    {
        string test = "test";

        //string as char array:
        //iterate through char collection
        foreach (char c in test)
        {
           //do something
        }
        //access elements by index
        Console.WriteLine("Contents of char array : {0}, {1}, {2}, {3}", test[0], test[1], test[2], test[3]);
        Console.ReadKey();
    }
}

Upvotes: 0

Koder101
Koder101

Reputation: 892

My general solution involves without using 'foreach' or 'StringBuilder' (which are C# specific) or without catching any exception.

            string str = "wordcounter";
            str += '\0';
            int x = 0;
            while (str[x] != '\0')
                x++;
            Console.WriteLine(x);     //Outputs 11

Upvotes: 0

karthikeyan
karthikeyan

Reputation: 1

class Program
 {
    static void Main(string[] args)
    {
        Console.WriteLine("Enter a string to find its lenght");
        string ch = Console.ReadLine();
        Program p = new Program();
        int answer = p.run(ch);
        Console.WriteLine(answer);
        Console.ReadKey();
    }
    public int run(string ch)
    {
        int count = 0;
        foreach (char c in ch)
        {
            count++;
        }
        return count;
    }
}

Upvotes: 0

Dennis Abragam
Dennis Abragam

Reputation: 11

class Program
{
    static void Main(string[] args)
    {

        string Name = "He is palying in a ground.";
        char[] characters = Name.ToCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = Name.Length - 1; i >= 0; --i)
        {
            sb.Append(characters[i]);
        }
        Console.Write(sb.ToString());
        Console.Read();

    }
}

Upvotes: 1

ykm29
ykm29

Reputation: 333

My answer is bit late, but I would like to post the same. Though all above mentioned solutions are correct, but I believe that the IL of the foreach does knows about the length of the iterable before iterating it. Talking of a pure solution, here's mine:

    private int stringLength(string str) {
        int length = 0;
        bool done = false;
        do {
            try {
                char c = str[length];
                length++;
            } catch (IndexOutOfRangeException) {
                done = true;
            }
        } while(!done);
        return length;
    }

Upvotes: 7

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

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.

Upvotes: 13

Stefano
Stefano

Reputation: 4031

not very fast but yo can always loop and count the number of caracter contained.

int counter = 0;
foreach (var caracter in str)
{
    counter ++;
}

Upvotes: 4

Kornelije Petak
Kornelije Petak

Reputation: 9572

How about?

int myOwnGetStringLength(String str)
{
    int count = 0;
    foreach(Char c in str)
        count++;
    return count;
}

Upvotes: 4

Related Questions