0

i did something. when i go through this algorithm on a paper, it makes sense... where am i wrong? i can't use trim method because the task is to use a while loop i know i'm kinda stupid 'cause i can't figure out this simplest task, but thank you in advance to anyone who'll explain this thing!

public static string RemoveStartSpaces(string text)
{
    int i = 0;
    while (char.IsWhiteSpace(text[i]))
    {
        i++;
        text.Substring(i);
    }
    return text;
}
  • 2
    Just use `.Trim` or `.TrimStart`. Internally `char.IsWhiteSpace` will be used by default. [Source](https://learn.microsoft.com/en-us/dotnet/api/system.string.trim?view=net-6.0#system-string-trim) – ProgrammingLlama Jun 27 '22 at 14:20
  • the task is to remove whitespaces using while loop :( – Julia Tryshkova Jun 27 '22 at 14:22
  • You can do that too. Just don't discard the result of `text.Substring` :) [This question](https://stackoverflow.com/questions/1948978/string-replace-or-other-string-modification-not-working) that I marked yours as a duplicate of will explain your issue. Also, you might want `Substring` _after_ the loop. – ProgrammingLlama Jun 27 '22 at 14:25
  • 1
    @JuliaTryshkova is this homework? Because it makes no sense to use a loop for this. Strings are immutable so any attempt to modify a string creates a new one, it doesn't modify the existing one. `test.Substring(i)` creates a new substring. You can use a loop to find the first non-whitespace character in that string and *outside* the loop, use `return test.Substring(i);` – Panagiotis Kanavos Jun 27 '22 at 14:29

0 Answers0