C#: Check if a string starts with a specified word
Check String Starts with Word
Write a C# program to check if a string starts with a specified word.
Note: Suppose the sentence starts with "Hello"
Sample Data: string1 = "Hello how are you?"
Result: Hello.

Sample Solution:-
C# Sharp Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class Exercise34 {
static void Main(string[] args) {
// Declare a string variable 'str' to store user input
string str;
// Display a message asking the user to input a string
Console.Write("Input a string : ");
// Read user input and store it in the 'str' variable
str = Console.ReadLine();
// Check conditions and output result based on string content
// Check if the length of the string is less than 6 and it's equal to "Hello"
// OR check if the string starts with "Hello" and the character at index 5 is a space (' ')
Console.WriteLine((str.Length < 6 && str.Equals("Hello")) || (str.StartsWith("Hello") && str[5] == ' '));
}
}
Sample Output:
Input a string : Hello how are you? True
Flowchart:

For more Practice: Solve these Related Problems:
- Write a C# program to check if a given string starts with a user-defined substring, case-insensitively.
- Write a C# program to validate if a sentence starts with a specific word and ends with a punctuation mark.
- Write a C# program to find how many times a string starts with a given word in a list of sentences.
- Write a C# program to check if a sentence starts with a certain word and contains another keyword later on.
Go to:
PREV : Check Multiple of 3 or 7.
NEXT : Check Numbers Less than 100 & Greater than 200.
C# Sharp Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.