Bird
0
0

You want to extract the first word from a sentence stored in string sentence. Which code correctly extracts the first word assuming words are separated by spaces?

hard🚀 Application Q15 of 15
C Sharp (C#) - Strings and StringBuilder
You want to extract the first word from a sentence stored in string sentence. Which code correctly extracts the first word assuming words are separated by spaces?
Astring firstWord = sentence.Substring(sentence.IndexOf(' ') + 1);
Bstring firstWord = sentence.Substring(0, sentence.IndexOf(' '));
Cint spacePos = sentence.IndexOf(' '); string firstWord = sentence.Substring(spacePos);
Dint spacePos = sentence.IndexOf(' '); string firstWord = spacePos == -1 ? sentence : sentence.Substring(0, spacePos);
Step-by-Step Solution
Solution:
  1. Step 1: Find position of first space

    Use IndexOf(' ') to find where the first space is.
  2. Step 2: Extract substring from start to space or whole string if no space

    If no space found (-1), the whole sentence is one word; else extract from 0 to space position.
  3. Final Answer:

    int spacePos = sentence.IndexOf(' '); string firstWord = spacePos == -1 ? sentence : sentence.Substring(0, spacePos); -> Option D
  4. Quick Check:

    Check for space, then substring from start [OK]
Quick Trick: Check if space exists before substring to avoid errors [OK]
Common Mistakes:
MISTAKES
  • Not handling case when no space exists
  • Extracting substring after space instead of before
  • Using wrong substring parameters

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes