-2

Is there any standard C# variable for whitespace? Something similar to Environment.NewLine. I didn't find anything online. I want to find the index of a whitespace in a given string.

For example

I can do string.indexOf(" ")

But I was wondering if there is anything in-built variable in C#.

KingJames
  • 546
  • 2
  • 9
  • 20
  • Adding more to your question might aid others in helping. Why do you need something to provide whitespace? What have you attempted or looked at? – confusedandamused Mar 30 '18 at 22:38
  • What all do you consider whitespace? Just space and horizontal tab? – itsme86 Mar 30 '18 at 22:52
  • just space is good for me. – KingJames Mar 30 '18 at 22:53
  • 2
    If you want only space, what you have is fine, or, if you want to use a C# defined value, try the answer provided by Mustafa Çetin below. As pointed out by itsme86 "white space" can mean more than a single space. This is also covered by Jon Skeet in an answer to a similar question here: https://stackoverflow.com/questions/11019561/how-to-correctly-represent-a-whitespace-character – user7396598 Mar 30 '18 at 22:58
  • The only reason Newline exists is because it is actually variable, operating systems do no agree about what a line-ending should look like. Nobody disagrees about an ascii space. Or the many Unicode spaces. I probably should not mention the [Space() method](https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.strings.space(v=vs.110).aspx) in everybody's favorite utility namespace, that would be gauche. – Hans Passant Mar 30 '18 at 23:58

2 Answers2

2

I am not sure if there in-built variable or function but maybe this can help you

int indexOfWhiteSpace(string input) {
    for (var i = 0; i < input.Length; i++) {
        if (char.IsWhiteSpace(input[i])) {
            return i;
        }
    }
    return -1;
}
Mustafa Çetin
  • 311
  • 2
  • 10
  • 3
    OP should note that this is more than just a space - https://msdn.microsoft.com/en-us/library/system.char.iswhitespace(v=vs.110).aspx – Matt Mar 30 '18 at 23:36
  • But he already want more than just a space so what is problem. I didt understand what you mean – Mustafa Çetin Mar 31 '18 at 10:55
0

An alternative would be

text.TakeWhile(c => !char.IsWhiteSpace(c)).Count();

Although just seen that you said it's only space you are after so I think your original code is fine. I guess you could do:

test.IndexOf(' ');

Which would keep it to a single character (but probably make little difference other than ensure you didn't accidentally type two spaces!)

d219
  • 2,707
  • 5
  • 31
  • 36