C#: Create a new string where 'if' is added to the front of a given string
Add 'if' to String if Absent
Write a C# Sharp program to create a string where 'if' is added to the front of a given string. If the string already begins with 'if', return it unchanged.
Visual Presentation:

Sample Solution:
C# Sharp Code:
using System;
// Namespace declaration
namespace exercises
{
// Class declaration
class Program
{
// Main method - entry point of the program
static void Main(string[] args)
{
// Calling the 'test' method with different strings and displaying the returned values
Console.WriteLine(test("if else")); // Output: "if else"
Console.WriteLine(test("else")); // Output: "if else"
Console.ReadLine(); // Keeping the console window open
}
// Method to modify the string based on a condition
public static string test(string s)
{
// Checking if the length of the string is greater than 2 and if the substring from index 0 to 1 is "if"
if (s.Length > 2 && s.Substring(0, 2).Equals("if"))
{
return s; // If the condition is true, return the original string 's'
}
return "if " + s; // If the condition is false, prepend "if " to the string 's' and return it
}
}
}
Sample Output:
if else if else
Flowchart:

For more Practice: Solve these Related Problems:
- Write a C# program to add 'else' at the end of a string if it doesn’t already end with 'else'.
- Write a C# program to add 'if' at both the beginning and end of the string only if it doesn’t start or end with it.
- Write a C# program that checks if the string starts with 'if' and ends with 'then'; if not, adds them accordingly.
- Write a C# program to insert 'if' at the second position of a string if it doesn’t already appear there.
Go to:
PREV : Within 10 of 100 or 200.
NEXT : Remove Character at Position.
C# Sharp Code Editor:
Improve this sample solution and post your code through Disqus
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.