Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Hi i'm a newbie in c# and i'm trying to write trimleft function by myself

public static string TrimLeft(string word)
    {
        int numberOfLetters = 0;
        foreach (var c in word)
        {
            numberOfLetters++;
        }

        int start = 0, end = numberOfLetters - 1;
        string b = "";
        for (int i = 0; i < numberOfLetters; i++)
        {
            if (!char.IsWhiteSpace(word[i]))
           {
                start = i;

                b += word[i];
            }
            
        }


        Console.WriteLine("Trimmed version: {0}", b);
        return word;
    }

i’m trying to write trimleft function by myself i couldnt quite figure out how i did the normal trim version but how can i do the trimleft version of it without using any inbuilt string. functions like substring etc.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this is a shorter version, it was tested and working properly

public static string TrimLeft(string word)
{
    string result = "";
    bool trimDone = false;

    foreach (var chr in word)
    {
        if (chr == ' ' && !trimDone) continue;
            result = result + chr;
            trimDone = true;
    }
    Console.WriteLine("Trimmed version: {0}", result);
    return result;
}

test

var word = "  abc def !";
word = TrimLeft(word);

result

abc def !

Somebody could suggest a string builder, but as I understand it is out of the scope of the project

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading