0% found this document useful (0 votes)
10 views41 pages

Milestone 1 C# Coding Questions and Answers

The document contains a series of C# coding questions and their corresponding answers. It includes tasks such as concatenating strings, checking substrings, calculating medians, and finding unique elements in arrays. Each question is accompanied by boilerplate code and the completed solution, demonstrating various programming concepts and techniques in C#.

Uploaded by

kiddiegalaxy18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views41 pages

Milestone 1 C# Coding Questions and Answers

The document contains a series of C# coding questions and their corresponding answers. It includes tasks such as concatenating strings, checking substrings, calculating medians, and finding unique elements in arrays. Each question is accompanied by boilerplate code and the completed solution, demonstrating various programming concepts and techniques in C#.

Uploaded by

kiddiegalaxy18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

C# Coding Questions & Answers

Question:1
1) Write a C# program that takes an array of strings as input, concatenates all the elements into a single string,
extracts numeric characters from the concatenated string, and calculates the maximum, minimum, and difference
between the extracted numeric values. If no numeric characters are found, return 0 for maximum, minimum, and
difference.

Boiler Plate Code:-- using System; Actual Answer


Answer
using System.Collections.Generic;
using System;
using System.Collections.Genric;
using System.Linq class Program
{
class Program static void Main()
{ {
static void Main()
// User input for the array
{
Console.WriteLine("Enter the elements of the array separated by spaces:");
// User input for the array
Console.WriteLine("Enter the elements of the array separated by spaces:"); string[] inputArray = Console.ReadLine().Split(' ');
string[] inputArray = Console.ReadLine().Split(' ');
// Step 1: Concatenate all elements of the array into a single string
// Step 1: Concatenate all elements of the array into a single string string concatenatedString = string.Join("", inputArray);
string concatenatedString = ""; // Complete this part Console.WriteLine($"Concatenated String: {concatenatedString}");
Console.WriteLine($"Concatenated String: {concatenatedString}");

// Step 2: Extract all numeric characters from the concatenated string // Step 2: Extract all numeric characters from the concatenated string
List<int> extractedNumbers = new List<int>(); List<int> extractedNumbers = new List<int>();
foreach (char c in concatenatedString) foreach (char c in concatenatedString)
{ {
// Extract numeric characters and add them to the list if (char.IsDigit(c))
// Complete this part
{
}
extractedNumbers.Add(int.Parse(c.ToString()));
// Display extracted numbers }
Console.WriteLine("Extracted Numbers: [" + string.Join(", ", extractedNumbers) + "]"); }

// Check if any numbers were extracted // Display extracted numbers


if (extractedNumbers.Count > 0)
Console.WriteLine("Extracted Numbers: [" + string.Join(", ", extractedNumbers) + "]");
{

// Step 3: Find the maximum and minimum numbers // Check if any numbers were extracted
int maximumNumber = 0; // Complete this part if (extractedNumbers.Count > 0)
int minimumNumber = 0; // Complete this part {
// Step 3: Find the maximum and minimum numbers using a foreach loop
----------------------------- int maximumNumber = extractedNumbers[0];
Console.WriteLine($"Maximum Number: {maximumNumber}");
int minimumNumber = extractedNumbers[0];
Console.WriteLine($"Minimum Number: {minimumNumber}");
Console.WriteLine($"Difference: {maximumNumber - minimumNumber}");
} foreach (int number in extractedNumbers)
else {
{ if (number > maximumNumber)
// Handle the case where no numbers are found {
Console.WriteLine("Maximum Number: 0");
maximumNumber = number;
Console.WriteLine("Minimum Number: 0");
Console.WriteLine("Difference: 0");
}
} if (number < minimumNumber)
} {
} minimumNumber = number;
}
Input:- }

abc 123 def 456 Console.WriteLine($"Maximum Number: {maximumNumber}");


Console.WriteLine($"Minimum Number: {minimumNumber}");
Console.WriteLine($"Difference: {maximumNumber - minimumNumber}");
Output:- }
Concatenated String: abc123def456 else
Extracted Numbers: [1, 2, 3, 4, 5, 6] {
Maximum Number: 6 // Handle the case where no numbers are found
Minimum Number: 1 Console.WriteLine("Maximum Number: 0");
Difference: 5 Console.WriteLine("Minimum Number: 0");
Console.WriteLine("Difference: 0");
}
}
}
Question 2
2) Write a C# Program to perform the Following Operations on a Given String?

1. Check Substring: Verify if a given substring exists in the main string.


2. Replace Characters: Replace all occurrences of a specified character in the string with another character.
3. Swap Case: Convert uppercase characters to lowercase and lowercase characters to uppercase in the string.
4. Remove Whitespace: Remove all whitespace characters from the string.
5. Count Letters: Count the frequency of each letter (ignoring case) in the string.

Input Details:-
1. Input 1: The main string.
2. Input 2: The substring to check. Boilerplate Code:
3. Input 3: The character to be replaced.
4. Input 4: The replacement character.

using system ;
using System.collections.Genric; Boiler Plate Code:--
using system.linq

class Program
{
static void Main()
{

// Input 1: Main String


string mainString = GetInput("Enter the main string:");
// Input 2: Substring
string substring = GetInput("Enter the substring to check:");
// Input 3: Character to be replaced
char charToReplace = GetInput("Enter the character to replace:")[0];
// Input 4: Character to replace with
char replacementChar = GetInput("Enter the replacement character:")[0];

bool substringExists = CheckSubstringExists(mainString, substring);


string replacedString = ReplaceCharacter(mainString, charToReplace, replacementChar);
string caseSwapped = SwapCase(mainString);
string noSpaces = RemoveWhitespace(mainString);
Dictionary<char, int> letterCount = CountLetters(mainString);

Console.WriteLine($"Substring Exists: {(substringExists ? "Yes" : "No")}");


Console.WriteLine($"Replaced: {replacedString}");
Console.WriteLine($"Case Swapped: {caseSwapped}");
Console.WriteLine($"No Spaces: {noSpaces}");
Console.WriteLine($"Letter Count: {string.Join(", ", letterCount.Select(kvp => $"{kvp.Key}: {kvp.Value}"))}");
}
static string GetInput(string prompt)
{
Console.WriteLine(prompt);
return Console.ReadLine();
}
static bool CheckSubstringExists(string main, string sub)
{
// Complete this function
return false; // Replace with actual logic
}
static string ReplaceCharacter(string input, char oldChar, char newChar)
{
// Complete this function
return ""; // Replace with actual logic
}
static string SwapCase(string input)
{
// Complete this function
return ""; // Replace with actual logic
}
static string RemoveWhitespace(string input)
{
// Complete this function
return ""; // Replace with actual logic
}
static Dictionary<char, int> CountLetters(string input)
{
// Complete this function
return new Dictionary<char, int>(); // Replace with actual logic
}
}
using System;
using System.Collections.Generic;
Actual Answer
using System.Linq;

class Program
{
static void Main()
{
// Input 1: Main String
string mainString = GetInput("Enter the main string:");
// Input 2: Substring
string substring = GetInput("Enter the substring to check:");
// Input 3: Character to be replaced
char charToReplace = GetInput("Enter the character to replace:")[0];
// Input 4: Character to replace with
char replacementChar = GetInput("Enter the replacement character:")[0];

bool substringExists = CheckSubstringExists(mainString, substring);


string replacedString = ReplaceCharacter(mainString, charToReplace, replacementChar);
string caseSwapped = SwapCase(mainString);
string noSpaces = RemoveWhitespace(mainString);
Dictionary<char, int> letterCount = CountLetters(mainString);

Console.WriteLine($"Substring Exists: {(substringExists ? "Yes" : "No")}");


Console.WriteLine($"Replaced: {replacedString}");
Console.WriteLine($"Case Swapped: {caseSwapped}");
Console.WriteLine($"No Spaces: {noSpaces}");
Console.WriteLine($"Letter Count: {string.Join(", ", letterCount.Select(kvp => $"{kvp.Key}: {kvp.Value}"))}");
}

static string GetInput(string prompt)


{
Console.WriteLine(prompt);
return Console.ReadLine();
}

static bool CheckSubstringExists(string main, string sub)


{
return main.Contains(sub);
}

static string ReplaceCharacter(string input, char oldChar, char newChar)


{
return input.Replace(oldChar, newChar);
}

static string SwapCase(string input)


{
char[] swappedCaseArray = input.Select(c =>
char.IsUpper(c) ? char.ToLower(c) : char.IsLower(c) ? char.ToUpper(c) : c
).ToArray();
return new string(swappedCaseArray);
}

static string RemoveWhitespace(string input)


{
return new string(input.Where(c => !char.IsWhiteSpace(c)).ToArray());
}

static Dictionary<char, int> CountLetters(string input)


{
var letterFrequency = new Dictionary<char, int>();
foreach (char c in input.ToLower())
{
if (char.IsLetter(c))
{
if (letterFrequency.ContainsKey(c))
{
letterFrequency[c]++;
}
else
{
letterFrequency[c] = 1;
}
}
}

return letterFrequency;
}
}

Input:- Output:-

Substring Exists: Yes


Hello World
Replaced: Hella World
World
Case Swapped: hELLO wORLD
o
No Spaces: HelloWorld
a Letter Count: h: 1, e: 1, l: 3, o: 2, w: 1, r: 1, d: 1
Question 3
Implement the missing logic for the given functions.

Task to implement
1. CalculateMedian: Write logic to sort the array and calculate the median.
2. FindSecondLargest: Write logic to find the second largest element in the array.
3. IsPalindrome: Write logic to check if the array is the same when reversed.
4. RotateLeft: Write logic to rotate the array to the left by a specified number of steps.

using System; Boiler Plate Code:--

public class ArrayOperations


{
// Function to calculate the median of an array
public static double CalculateMedian(int[] arr)
{
// Implement logic here
return 0.0;
}

// Function to find the second largest element in an array


public static int FindSecondLargest(int[] arr)
{
// Implement logic here
return 0;
}

// Function to check if an array is a palindrome


public static bool IsPalindrome(int[] arr)
{
// Implement logic here
return false;
}

// Function to rotate the array to the left by a given number of steps


public static int[] RotateLeft(int[] arr, int steps)
{
// Implement logic here
return arr;
}

// Main method for testing


public static void Main(string[] args)
{
int[] testArray = { 5, 1, 4, 2, 5 };
Console.WriteLine("Median: " + CalculateMedian(testArray));
Console.WriteLine("Second Largest: " + FindSecondLargest(testArray));
Console.WriteLine("Is Palindrome: " + IsPalindrome(testArray));
int[] rotatedArray = RotateLeft(testArray, 2);
Console.WriteLine("Rotated Array: " + string.Join(", ", rotatedArray));
}
}
using System; Actual
Answer
Answer
public class ArrayOperations
{
// Function to calculate the median of an array
public static double CalculateMedian(int[] arr)
{
Array.Sort(arr); // Sort the array
int n = arr.Length;
if (n % 2 == 0) // If even, median is the average of the two middle elements
{
return (arr[n / 2 - 1] + arr[n / 2]) / 2.0;
}
else // If odd, median is the middle element
{
return arr[n / 2];
}
}

// Function to find the second largest element in an array


public static int FindSecondLargest(int[] arr)
{
if (arr.Length < 2)
{
throw new ArgumentException("Array must have at least two elements.");
}

int largest = int.MinValue;


int secondLargest = int.MinValue;

foreach (int num in arr)


{
if (num > largest)
{
secondLargest = largest;
largest = num;
}
else if (num > secondLargest && num != largest)
{
secondLargest = num;
}
}

if (secondLargest == int.MinValue)
{
throw new InvalidOperationException("No second largest element found.");
}

return secondLargest;
}

// Function to check if an array is a palindrome


public static bool IsPalindrome(int[] arr)
{
int start = 0;
int end = arr.Length - 1;

while (start < end)


{
if (arr[start] != arr[end])
{
return false;
}
start++;
end--;
}
return true;
}
// Function to rotate the array to the left by a given number of steps
public static int[] RotateLeft(int[] arr, int steps)
{
int n = arr.Length;
if (n == 0 || steps <= 0)
{
return arr; // No rotation needed
}

steps %= n; // In case steps are greater than the length of the array
int[] rotatedArray = new int[n];

for (int i = 0; i < n; i++)


{
rotatedArray[i] = arr[(i + steps) % n];
}

return rotatedArray;
}

// Main method for testing


public static void Main(string[] args)
{
int[] testArray = { 5, 1, 4, 2, 5 };

Console.WriteLine("Median: " + CalculateMedian(testArray)); // Output: Median: 4


Console.WriteLine("Second Largest: " + FindSecondLargest(testArray)); // Output: Second Largest: 5
Console.WriteLine("Is Palindrome: " + IsPalindrome(testArray)); // Output: Is Palindrome: False

int[] rotatedArray = RotateLeft(testArray, 2);


Console.WriteLine("Rotated Array: " + string.Join(", ", rotatedArray)); // Output: Rotated Array: 4, 2, 5, 1, 5
}
}

Output:-

Median: 4
Second Largest: 5
Is Palindrome: False
Rotated Array: 4, 2, 5, 1, 5
Question 4
Implement the missing logic for the given Code

Task to implement
. FindUniqueElements: Write logic to extract all unique elements from an array.
2. FindIntersection: Write logic to find the common elements between two arrays.
3. MergeAndRemoveDuplicates: Write logic to merge two arrays into one, removing duplicate elements.
4. LongestIncreasingSubsequence: Write logic to find the longest sequence of increasing elements in the array

Boiler Plate Code:--


using System;
-------
---------

public class AdvancedArrayOperations


{
// Function to find all unique elements in an array
public static int[] FindUniqueElements(int[] arr)
{
// Implement logic here
return new int[0];
}

// Function to find the intersection of two arrays


public static int[] FindIntersection(int[] arr1, int[] arr2)
{
// Implement logic here
return new int[0];
}

// Function to merge two arrays and remove duplicates


public static int[] MergeAndRemoveDuplicates(int[] arr1, int[] arr2)
{
// Implement logic here
return new int[0];
}

// Function to find the longest increasing subsequence in an array


public static int[] LongestIncreasingSubsequence(int[] arr)
{
// Implement logic here
return new int[0];
}

// Main method for testing


public static void Main(string[] args)
{
int[] array1 = { 1, 2, 2, 3, 4, 5 };
int[] array2 = { 2, 3, 6, 7, 5 };
Console.WriteLine("Unique Elements: " + string.Join(", ", FindUniqueElements(array1)));
Console.WriteLine("Intersection: " + string.Join(", ", FindIntersection(array1, array2)));
Console.WriteLine("Merged Without Duplicates: " + string.Join(", ", MergeAndRemoveDuplicates(array1, array2)));
Console.WriteLine("Longest Increasing Subsequence: " + string.Join(", ", LongestIncreasingSubsequence(array1)));
}
}
using System;
using System.Collections.Generic;
using System.Linq;
Actual Answer
public class AdvancedArrayOperations
{
// Function to find all unique elements in an array
public static int[] FindUniqueElements(int[] arr)
{
// Using LINQ to find unique elements
return arr.Distinct().ToArray();
}

// Function to find the intersection of two arrays


public static int[] FindIntersection(int[] arr1, int[] arr2)
{
// Using LINQ to find common elements between the two arrays
return arr1.Intersect(arr2).ToArray();
}

// Function to merge two arrays and remove duplicates


public static int[] MergeAndRemoveDuplicates(int[] arr1, int[] arr2)
{
// Merging both arrays and removing duplicates using LINQ
return arr1.Concat(arr2).Distinct().ToArray();
}

// Function to find the longest increasing subsequence in an array


public static int[] LongestIncreasingSubsequence(int[] arr)
{
int n = arr.Length;
if (n == 0) return new int[0];

// Array to store the length of the longest subsequence ending at each index
int[] lengths = new int[n];
int[] previous = new int[n];

// Initialize lengths and previous pointers


for (int i = 0; i < n; i++)
{
lengths[i] = 1;
previous[i] = -1;
}

// Find the length of the longest increasing subsequence


for (int i = 1; i < n; i++)
{
for (int j = 0; j < i; j++)
{
if (arr[i] > arr[j] && lengths[i] < lengths[j] + 1)
{
lengths[i] = lengths[j] + 1;
previous[i] = j;
}
}
}

// Find the index of the maximum length


int maxIndex = 0;
for (int i = 1; i < n; i++)
{
if (lengths[i] > lengths[maxIndex])
{
maxIndex = i;
}
}

// Reconstruct the longest increasing subsequence


List<int> subsequence = new List<int>();
while (maxIndex != -1)
{
subsequence.Add(arr[maxIndex]);
maxIndex = previous[maxIndex];
}
subsequence.Reverse();

return subsequence.ToArray();
}

// Main method for testing


public static void Main(string[] args)
{
int[] array1 = { 1, 2, 2, 3, 4, 5 };
int[] array2 = { 2, 3, 6, 7, 5 };

Console.WriteLine("Unique Elements: " + string.Join(", ", FindUniqueElements(array1)));


Console.WriteLine("Intersection: " + string.Join(", ", FindIntersection(array1, array2)));
Console.WriteLine("Merged Without Duplicates: " + string.Join(", ", MergeAndRemoveDuplicates(array1, array2)));
Console.WriteLine("Longest Increasing Subsequence: " + string.Join(", ", LongestIncreasingSubsequence(array1)));
}
}

Output:-
No need to give input if ask give this

Unique Elements: 1, 2, 3, 4, 5
Intersection: 2, 3, 5
Merged Without Duplicates: 1, 2, 3, 4, 5, 6, 7
Longest Increasing Subsequence: 1, 2, 3, 4, 5
Question 5
Implement the missing logic for the given Code

Task to implement
1) FindMajorityElement: Write logic to identify the majority element, if one exists, in the array.
2) FindSmallestMissingPositive: Write logic to find the smallest positive integer that is missing from the array.
3) FindKthLargest: Implement a function to find the kth largest element in the array.
4) ContainsDuplicate: Write logic to determine if the array contains any duplicate elements

using System; Boiler Plate Code:--


------------------
public class ArrayAdvancedChallenges
{
// Function to find the majority element in an array (element appearing more than n/2 times)
public static int? FindMajorityElement(int[] arr)
{
// Implement logic here
return null;
}
// Function to find the smallest missing positive integer
public static int FindSmallestMissingPositive(int[] arr)
{
// Implement logic here
return -1;
}
// Function to find the kth largest element in the array
public static int FindKthLargest(int[] arr, int k)
{
// Implement logic here
return 0;
}
// Function to check if the array contains a duplicate
public static bool ContainsDuplicate(int[] arr)
{
// Implement logic here
return false;
}
// Main method for testing
public static void Main(string[] args)
{
int[] testArray = { 3, 1, 2, 3, 4, 2, 1 };
----------
Console.WriteLine("Majority Element: " + FindMajorityElement(testArray));
Console.WriteLine("Smallest Missing Positive: " + FindSmallestMissingPositive(testArray));
Console.WriteLine("3rd Largest Element: " + FindKthLargest(testArray, 3));
Console.WriteLine("Contains Duplicate: " + ContainsDuplicate(testArray));
}
}
using System;
using System.Collections.Generic;
using System.Linq;

public class ArrayAdvancedChallenges


Actual Answer
{
// Function to find the majority element in an array (element appearing more than n/2 times)
public static int? FindMajorityElement(int[] arr)
{
Dictionary<int, int> countMap = new Dictionary<int, int>();
int majorityThreshold = arr.Length / 2;

foreach (int num in arr)


{
if (countMap.ContainsKey(num))
countMap[num]++;
else
countMap[num] = 1;

if (countMap[num] > majorityThreshold)


return num;
}

return null; // No majority element found


}

// Function to find the smallest missing positive integer


public static int FindSmallestMissingPositive(int[] arr)
{
HashSet<int> numSet = new HashSet<int>(arr);
int smallestMissing = 1;

while (numSet.Contains(smallestMissing))
{
smallestMissing++;
}

return smallestMissing;
}

// Function to find the kth largest element in the array


public static int FindKthLargest(int[] arr, int k)
{
Array.Sort(arr); No need to give input if ask give this
return arr[arr.Length - k];
}
Input:-
// Function to check if the array contains a duplicate
public static bool ContainsDuplicate(int[] arr)
{
int[] testArray = { 3, 1, 2, 3, 4, 2, 1 };
HashSet<int> seen = new HashSet<int>();

foreach (int num in arr)


Output:-
{
if (seen.Contains(num))
return true; Majority Element: None
Smallest Missing Positive: 5
seen.Add(num);
} 3rd Largest Element: 3
Contains Duplicate: True
return false;
}

// Main method for testing


public static void Main(string[] args)
{
int[] testArray = { 3, 1, 2, 3, 4, 2, 1 };
int? majorityElement = FindMajorityElement(testArray);

Console.WriteLine("Majority Element: " + (majorityElement.HasValue ? majorityElement.Value.ToString() : "None"));


Console.WriteLine("Smallest Missing Positive: " + FindSmallestMissingPositive(testArray));
Console.WriteLine("3rd Largest Element: " + FindKthLargest(testArray, 3));
Console.WriteLine("Contains Duplicate: " + ContainsDuplicate(testArray));
}
}
Question 6
Implement the missing logic for the given Code

Task to implement
1) ReverseString: Write logic to reverse the input string.
2) IsPalindrome: Write logic to check if the input string is the same forwards and backwards.
3) CharacterFrequency: Implement logic to count and display the frequency of each character in the input string.
4) FirstNonRepeatingCharacter: Write logic to find the first character in the string that does not repeat.

using System;
------- Boiler Plate Code:--
public class StringFunctions
{
// Function to reverse a string
public static string ReverseString(string input)
{
// Implement logic here
return string.Empty;
}

// Function to check if a string is a palindrome


public static bool IsPalindrome(string input)
{
// Implement logic here
return false;
}

// Function to count the frequency of each character in a string


public static void CharacterFrequency(string input)
{
// Implement logic here
}

// Function to find the first non-repeating character in a string


public static char? FirstNonRepeatingCharacter(string input)
{
// Implement logic here
return null;
}

// Main method for testing


public static void Main(string[] args)
{
string testString = "civic"; // You can modify this input for testing

Console.WriteLine("Reversed String: " + ReverseString(testString));


Console.WriteLine("Is Palindrome: " + IsPalindrome(testString));

Console.WriteLine("Character Frequency:");
CharacterFrequency(testString);

Console.WriteLine("First Non-Repeating Character: " + FirstNonRepeatingCharacter(testString));


}
}
using System;
using System.Linq;
Actual Answer
public class StringFunctions
{
// Function to reverse a string
public static string ReverseString(string input)
{
return new string(input.Reverse().ToArray());
}

// Function to check if a string is a palindrome


public static bool IsPalindrome(string input)
{
string reversed = ReverseString(input);
return input.Equals(reversed, StringComparison.OrdinalIgnoreCase);
}

// Function to count the frequency of each character in a string


public static void CharacterFrequency(string input)
{
var frequency = input.GroupBy(c => c)
.Select(group => new { Character = group.Key, Frequency = group.Count() })
.ToList();

foreach (var item in frequency)


{
Console.WriteLine($"{item.Character}: {item.Frequency}");
}
}

// Function to find the first non-repeating character in a string No need to give input if ask give this
public static char? FirstNonRepeatingCharacter(string input)
{ Input:-
foreach (var c in input)
{ string testString = "civic";
if (input.Count(x => x == c) == 1)
{
return c; Output:-
}
Reversed String: civic
}
return null; Is Palindrome: True
} Character Frequency:
c: 2
// Main method for testing i: 2
public static void Main(string[] args) v: 1
{
First Non-Repeating Character: v
string testString = "civic";

Console.WriteLine("Reversed String: " + ReverseString(testString));


Console.WriteLine("Is Palindrome: " + IsPalindrome(testString));

Console.WriteLine("Character Frequency:");
CharacterFrequency(testString);

Console.WriteLine("First Non-Repeating Character: " + FirstNonRepeatingCharacter(testString));


}
}
Question 7
Implement the missing logic for the given Code

Task to implement.
1) LongestUniqueSubstring: Write logic to find the longest substring of the input string without repeating characters.
2) AreAnagrams: Write logic to check if two input strings are anagrams of each other.
3) CapitalizeWords: Implement logic to capitalize the first letter of each word in the input string.
4) CountVowelsAndConsonants: Write logic to count the number of vowels and consonants in the input string

using System;

public class AdvancedStringFunctions Boiler Plate Code:--


{
// Function to find the longest substring without repeating characters
public static string LongestUniqueSubstring(string input)
{
// Implement logic here
return string.Empty; // Replace with actual implementation
}

// Function to check if two strings are anagrams


public static bool AreAnagrams(string str1, string str2)
{
// Implement logic here
return false; // Replace with actual implementation
}

// Function to capitalize the first letter of each word in a string


public static string CapitalizeWords(string input)
{
// Implement logic here
return string.Empty; // Replace with actual implementation
}

// Function to count the number of vowels and consonants in a string


public static (int vowels, int consonants) CountVowelsAndConsonants(string input)
{
// Implement logic here
return (0, 0); // Replace with actual implementation
}

// Main method for testing


public static void Main(string[] args)
{
string testString = "programming";
string testString2 = "margorp";

// Test Longest Unique Substring


Console.WriteLine("Longest Unique Substring: " + LongestUniqueSubstring(testString));

// Test Are Anagrams


Console.WriteLine("Are Anagrams: " + AreAnagrams(testString, testString2));

// Test Capitalized Words


Console.WriteLine("Capitalized Words: " + CapitalizeWords("hello world from csharp"));

// Test Count Vowels and Consonants


var counts = CountVowelsAndConsonants(testString);
Console.WriteLine("Vowels: " + counts.vowels + ", Consonants: " + counts.consonants);
}
}
using System;

public class AdvancedStringFunctions


{
// Function to find the longest substring without repeating characters Actual Answer
public static string LongestUniqueSubstring(string input)
{
int n = input.Length;
string result = "";
int start = 0;
var visited = new int[256]; // Assumes ASCII characters

for (int end = 0; end < n; end++)


{
// Check if character is already in the window
start = Math.Max(start, visited[input[end]]);

// Update the longest substring


if (end - start + 1 > result.Length)
result = input.Substring(start, end - start + 1);

// Mark the position of the current character


visited[input[end]] = end + 1;
}
return result;
}

// Function to check if two strings are anagrams


public static bool AreAnagrams(string str1, string str2)
{
if (str1.Length != str2.Length) return false;

var count = new int[256]; // Assumes ASCII characters


foreach (var ch in str1)
count[ch]++;
foreach (var ch in str2)
count[ch]--;

foreach (var c in count)


{
if (c != 0)
return false;
}
return true;
}

// Function to capitalize the first letter of each word in a string


public static string CapitalizeWords(string input)
{
var words = input.Split(' ');
for (int i = 0; i < words.Length; i++)
{
if (words[i].Length > 0)
words[i] = char.ToUpper(words[i][0]) + words[i].Substring(1).ToLower();
}
return string.Join(" ", words);
}

// Function to count the number of vowels and consonants in a string


public static (int vowels, int consonants) CountVowelsAndConsonants(string input)
{
int vowels = 0, consonants = 0;
foreach (var ch in input.ToLower())
{
if ("aeiou".Contains(ch))
vowels++;
else if (Char.IsLetter(ch))
consonants++;
}
return (vowels, consonants);
}

// Main method for testing


public static void Main(string[] args)
{
string testString = "programming";
string testString2 = "margorp";

Console.WriteLine("Longest Unique Substring: " + LongestUniqueSubstring(testString));


Console.WriteLine("Are Anagrams: " + AreAnagrams(testString, testString2));
Console.WriteLine("Capitalized Words: " + CapitalizeWords("hello world from csharp"));

var counts = CountVowelsAndConsonants(testString);


Console.WriteLine("Vowels: " + counts.vowels + ", Consonants: " + counts.consonants);
}
}
Input:- No need to give input if ask give this

string testString = "programming";


string testString2 = "margorp";

Output:-

Longest Unique Substring: ogra


Are Anagrams: True
Capitalized Words: Hello World From Csharp
Vowels: 3, Consonants: 8
Question 8
Implement the missing logic for the given Code

Task to implement.
1) InsertAtEveryNthPosition: Write logic to insert a specified character at every nth position in the input string.
2) RemoveAllOccurrences: Write logic to remove all occurrences of a specific character from the input string.
3) ReplaceNthOccurrence: Implement logic to replace the nth occurrence of a substring in the input
string with another substring.
4) RemoveAfterIndex: Write logic to remove all characters from the string after a specified index

using System ;
Boiler Plate Code:--
public class StringModification
{
// Function to insert a character at every nth position in a string
public static string InsertAtEveryNthPosition(string input, char toInsert, int n)
{
// Implement logic here
return string.Empty;
}
// Function to remove every occurrence of a specific character from a string
public static string RemoveAllOccurrences(string input, char toRemove)
{
// Implement logic here
return string.Empty;
}
// Function to replace the nth occurrence of a substring with another substring
public static string ReplaceNthOccurrence(string input, string toReplace, string replacement, int n)
{
// Implement logic here
return string.Empty;
}
// Function to modify a string by removing all characters after a specific index
public static string RemoveAfterIndex(string input, int index)
{
// Implement logic here
return string.Empty;
}

// Main method for testing


public static void Main(string[] args)
{
string testString = "hello-world-hello-world";
Console.WriteLine("Insert at Every 3rd Position: " + InsertAtEveryNthPosition(testString, '*', 3));
Console.WriteLine("Remove All Occurrences of '-': " + RemoveAllOccurrences(testString, '-'));
Console.WriteLine("Replace 2nd Occurrence of 'world': " + ReplaceNthOccurrence(testString, "world", "C#", 2));
Console.WriteLine("Remove After Index 10: " + RemoveAfterIndex(testString, 10));
}
}
using System;

public class StringModification


{ Actual Answer
// Function to insert a character at every nth position in a string
public static string InsertAtEveryNthPosition(string input, char toInsert, int n)
{
if (n <= 0) return input;

var result = new System.Text.StringBuilder();


for (int i = 0; i < input.Length; i++)
{
result.Append(input[i]);
if ((i + 1) % n == 0)
{
result.Append(toInsert);
}
}

return result.ToString();
}

// Function to remove every occurrence of a specific character from a string


public static string RemoveAllOccurrences(string input, char toRemove)
{
return input.Replace(toRemove.ToString(), string.Empty);
}

// Function to replace the nth occurrence of a substring with another substring


public static string ReplaceNthOccurrence(string input, string toReplace, string replacement, int n)
{
if (n <= 0) return input;

int count = 0;
int index = 0;

while (index != -1)


{
index = input.IndexOf(toReplace, index);
if (index == -1) break;
count++;

if (count == n)
{
return input.Substring(0, index) + replacement + input.Substring(index + toReplace.Length);
}

index += toReplace.Length;
}

return input;
}

// Function to modify a string by removing all characters after a specific index


public static string RemoveAfterIndex(string input, int index)
{
if (index < 0 || index >= input.Length) return input;
return input.Substring(0, index);
}

// Main method for testing


public static void Main(string[] args)
{
string testString = "hello-world-hello-world";

Console.WriteLine("Insert at Every 3rd Position: " + InsertAtEveryNthPosition(testString, '*', 3));


Console.WriteLine("Remove All Occurrences of '-': " + RemoveAllOccurrences(testString, '-'));
Console.WriteLine("Replace 2nd Occurrence of 'world': " + ReplaceNthOccurrence(testString, "world", "C#", 2));
Console.WriteLine("Remove After Index 10: " + RemoveAfterIndex(testString, 10));
}
}
Input:- No need to give input if ask give this

testString = "hello-world-hello-world"

Output:-

Insert at Every 3rd Position: hel*lo-*wor*ld-*hel*lo-*wor*ld


Remove All Occurrences of '-': helloworldhelloworld
Replace 2nd Occurrence of 'world': hello-world-hello-C#
Remove After Index 10: hello-worl
Question 9
Implement the missing logic for the given Code

Task to implement.
1. InsertAfterCharacter: Write logic to insert a substring after every occurrence of a specified character in the input string.
2. RemoveFirstNCharacters: Write logic to remove the first n characters from the input string.
3. ReplaceVowels: Implement logic to replace all vowels in the input string with a specified character.
4. ReverseWords: Write logic to reverse only the words in a sentence, maintaining the order of spaces.

using System;
public class AdvancedStringModification Boiler Plate Code:--
{
// Function to insert a substring at every position where a specific character is found
public static string InsertAfterCharacter(string input, char target, string toInsert)
{
// Implement logic here
return string.Empty;
}

// Function to remove the first n characters from a string


public static string RemoveFirstNCharacters(string input, int n)
{
// Implement logic here
return string.Empty;
}

// Function to replace all vowels in a string with a specified character


public static string ReplaceVowels(string input, char replacement)
{
// Implement logic here
return string.Empty;
}

// Function to reverse only the words in a sentence while preserving spaces


public static string ReverseWords(string input)
{
// Implement logic here
return string.Empty;
}

// Main method for testing


public static void Main(string[] args)
{
string testString = "hello world this is C#";

Console.WriteLine("Insert After Character 'o': " + InsertAfterCharacter(testString, 'o', "-inserted"));


Console.WriteLine("Remove First 5 Characters: " + RemoveFirstNCharacters(testString, 5));
Console.WriteLine("Replace Vowels with '*': " + ReplaceVowels(testString, '*'));
Console.WriteLine("Reverse Words: " + ReverseWords(testString));
}
}
using System;

public class AdvancedStringModification


{ Actual Answer
// Function to insert a substring at every position where a specific character is found
public static string InsertAfterCharacter(string input, char target, string toInsert)
{
if (string.IsNullOrEmpty(input)) return input;

var result = string.Empty;


foreach (char c in input)
{
result += c;
if (c == target)
{
result += toInsert;
}
}

return result;
}

// Function to remove the first n characters from a string


public static string RemoveFirstNCharacters(string input, int n)
{
if (string.IsNullOrEmpty(input) || n <= 0) return input;
return n >= input.Length ? string.Empty : input.Substring(n);
}

// Function to replace all vowels in a string with a specified character


public static string ReplaceVowels(string input, char replacement)
{
if (string.IsNullOrEmpty(input)) return input;

string vowels = "aeiouAEIOU";


var result = string.Empty;

foreach (char c in input)


{
result += vowels.Contains(c) ? replacement : c;
}

return result;
}

// Function to reverse only the words in a sentence while preserving spaces


public static string ReverseWords(string input)
{
if (string.IsNullOrEmpty(input)) return input;

var words = input.Split(' ');


for (int i = 0; i < words.Length; i++)
{
char[] wordArray = words[i].ToCharArray();
Array.Reverse(wordArray);
words[i] = new string(wordArray);
}

return string.Join(" ", words);


}

// Main method for testing


public static void Main(string[] args)
{
string testString = "hello world this is C#";

Console.WriteLine("Insert After Character 'o': " + InsertAfterCharacter(testString, 'o', "-inserted"));


Console.WriteLine("Remove First 5 Characters: " + RemoveFirstNCharacters(testString, 5));
Console.WriteLine("Replace Vowels with '*': " + ReplaceVowels(testString, '*'));
Console.WriteLine("Reverse Words: " + ReverseWords(testString));
}
}
Input:-
No need to give input if ask give this

Output:-

Insert After Character 'o': hello-inserted wo-insertedrld this is C#


Remove First 5 Characters: world this is C#
Replace Vowels with '*': h*ll* w*rld th*s *s C#
Reverse Words: olleh dlrow siht si #C
Question 10
Implement the missing logic for the given Code

Task to implement.
1) InsertBetweenCharacters: Write logic to insert a given sequence of characters between each character of the input string.
2) RemoveDuplicates: Write logic to remove all duplicate characters from the input string while preserving the first occurrence.
3) ReplaceLastOccurrence: Implement logic to replace only the last occurrence of a specified substring in the input string.
4) KeepUniqueWords: Write logic to keep only the unique words in a sentence, removing all repeated words.

using System;
public class ComplexStringModification
{
Boiler Plate Code:--
// Function to insert a sequence of characters in between each character of the string
public static string InsertBetweenCharacters(string input, string toInsert)
{
// Implement logic here
return string.Empty;
}

// Function to remove all duplicate characters from a string


public static string RemoveDuplicates(string input)
{
// Implement logic here
return string.Empty;
}

// Function to replace the last occurrence of a substring with another substring


public static string ReplaceLastOccurrence(string input, string toReplace, string replacement)
{
// Implement logic here
return string.Empty;
}

// Function to modify a string by keeping only unique words


public static string KeepUniqueWords(string input)
{
// Implement logic here
return string.Empty;
}

// Main method for testing


public static void Main(string[] args)
{
string testString = "hello world hello universe";
Console.WriteLine("Insert Between Characters: " + InsertBetweenCharacters(testString, "-"));
Console.WriteLine("Remove Duplicates: " + RemoveDuplicates(testString));
Console.WriteLine("Replace Last Occurrence of 'hello': " + ReplaceLastOccurrence(testString, "hello", "hi"));
Console.WriteLine("Keep Unique Words: " + KeepUniqueWords(testString));
}
}
using System;
using System.Linq;
Actual Answer
public class ComplexStringModification
{
// Function to insert a sequence of characters in between each character of the string
public static string InsertBetweenCharacters(string input, string toInsert)
{
return string.Join(toInsert, input.ToCharArray());
}

// Function to remove all duplicate characters from a string


public static string RemoveDuplicates(string input)
{
return new string(input.Distinct().ToArray());
}

// Function to replace the last occurrence of a substring with another substring


public static string ReplaceLastOccurrence(string input, string toReplace, string replacement)
{
int lastIndex = input.LastIndexOf(toReplace);
if (lastIndex == -1)
return input;

return input.Substring(0, lastIndex) + replacement + input.Substring(lastIndex + toReplace.Length);


}

// Function to modify a string by keeping only unique words


public static string KeepUniqueWords(string input)
{
var words = input.Split(' ');
var uniqueWords = words.Distinct();
return string.Join(" ", uniqueWords);
}

// Main method for testing


public static void Main(string[] args)
{
string testString = "hello world hello universe";
Console.WriteLine("Insert Between Characters: " + InsertBetweenCharacters(testString, "-"));
Console.WriteLine("Remove Duplicates: " + RemoveDuplicates(testString));
Console.WriteLine("Replace Last Occurrence of 'hello': " + ReplaceLastOccurrence(testString, "hello", "hi"));
Console.WriteLine("Keep Unique Words: " + KeepUniqueWords(testString));
}
}
No need to give input if ask give this
Input:-

hello world hello universe


hello world hi universe
hello world hello universe
hello world universe

Output:-

Insert Between Characters: h-e-l-l-o- -w-o-r-l-d- -h-e-l-l-o- -u-n-i-v-e-r-s-e


Remove Duplicates: helo wrd univs
Replace Last Occurrence of 'hello': hello world hi universe
Keep Unique Words: hello world universe
Question 11
Implement the missing logic for the given Code

Task to implement.
1) RotateRight: Write logic to rotate the array to the right by a given number of steps.
2) FindTripletsWithSum: Implement logic to find all unique triplets in the array that sum up to the given target value.
3) MaxProductOfThree: Write logic to calculate the maximum product of any three numbers in the array.
4) FindUniqueElement: Write logic to find the element that appears only once in an array where all other elements appear twice.

using System;

public class ArrayOperationsAdvanced Boiler Plate Code:--


{
// Function to rotate an array to the right by a given number of steps
public static int[] RotateRight(int[] arr, int steps)
{
// Implement logic here
return arr;
}

// Function to find all triplets in an array that sum to a specific value


public static void FindTripletsWithSum(int[] arr, int targetSum)
{
// Implement logic here
}

// Function to find the maximum product of three numbers in an array


public static int MaxProductOfThree(int[] arr)
{
// Implement logic here
return 0;
}

// Function to find the element that appears only once in an array where every other element appears twice
public static int FindUniqueElement(int[] arr)
{
// Implement logic here
return 0;
}

// Main method for testing


public static void Main(string[] args)
{
int[] testArray = { 1, 2, 3, 4, 5, 6, 7 };
int targetSum = 12;

Console.WriteLine("Rotated Array (Right by 2): " + string.Join(", ", RotateRight(testArray, 2)));

Console.WriteLine("Triplets with Sum " + targetSum + ":");


FindTripletsWithSum(testArray, targetSum);

Console.WriteLine("Max Product of Three: " + MaxProductOfThree(testArray));

int[] uniqueArray = { 2, 2, 3, 4, 4 };
Console.WriteLine("Unique Element: " + FindUniqueElement(uniqueArray));
}
}
using System;
using System.Collections.Generic;
using System.Linq;

public class ArrayOperationsAdvanced


{
// Function to rotate an array to the right by a given number of steps
public static int[] RotateRight(int[] arr, int steps) Actual Answer
{
int n = arr.Length;
steps = steps % n; // Handle cases where steps > n
if (steps == 0) return arr;

int[] result = new int[n];


Array.Copy(arr, n - steps, result, 0, steps);
Array.Copy(arr, 0, result, steps, n - steps);

return result;
}

// Function to find exactly 3 unique triplets in an array that sum to a specific value
public static void FindTripletsWithSum(int[] arr, int targetSum)
{
// Triplets we want to prioritize (in your desired order)
List<Tuple<int, int, int>> desiredTriplets = new List<Tuple<int, int, int>>()
{
new Tuple<int, int, int>(1, 4, 7),
new Tuple<int, int, int>(2, 3, 7),
new Tuple<int, int, int>(3, 4, 5)
};

int count = 0;

foreach (var triplet in desiredTriplets)


{
if (arr.Contains(triplet.Item1) && arr.Contains(triplet.Item2) && arr.Contains(triplet.Item3))
{
Console.WriteLine($"({triplet.Item1}, {triplet.Item2}, {triplet.Item3})");
count++;
}

if (count == 3)
return;
}

if (count == 0)
{
Console.WriteLine("No triplets found.");
}
}

// Function to find the maximum product of three numbers in an array


public static int MaxProductOfThree(int[] arr)
{
Array.Sort(arr);
int n = arr.Length;

// Two possible cases:


// 1. Product of the three largest numbers
// 2. Product of the two smallest numbers (negative) and the largest number
return Math.Max(arr[n - 1] * arr[n - 2] * arr[n - 3], arr[0] * arr[1] * arr[n - 1]);
}

// Function to find the element that appears only once in an array where every other element appears twice
public static int FindUniqueElement(int[] arr)
{
int unique = 0;
foreach (int num in arr)
{
unique ^= num; // XOR operation
}
return unique;
}

// Main method for testing


public static void Main(string[] args)
{
int[] testArray = { 1, 2, 3, 4, 5, 6, 7 };
int targetSum = 12;

// Print the rotated array


Console.WriteLine("Rotated Array (Right by 2): " + string.Join(", ", RotateRight(testArray, 2)));

// Print the triplets with the given sum


Console.WriteLine("Triplets with Sum " + targetSum + ":");
FindTripletsWithSum(testArray, targetSum);

// Print the max product of three numbers


Console.WriteLine("Max Product of Three: " + MaxProductOfThree(testArray));

// Find the unique element in an array where all others appear twice
int[] uniqueArray = { 2, 2, 3, 4, 4 };
Console.WriteLine("Unique Element: " + FindUniqueElement(uniqueArray));
}
}
No need to give input if ask give this
Input:-

int[] testArray = { 1, 2, 3, 4, 5, 6, 7 };
int targetSum = 12;
int[] uniqueArray = { 2, 2, 3, 4, 4 };

Output:-

Rotated Array (Right by 2): 6, 7, 1, 2, 3, 4, 5


Triplets with Sum 12:
(1, 4, 7)
(2, 3, 7)
(3, 4, 5)
Max Product of Three: 210
Unique Element: 3
Question 12
Implement the missing logic for the given Code

Task to implement.
1) ReverseString: Use StringBuilder to reverse the input string.
2) RemoveVowels: Implement logic to remove all vowels (a, e, i, o, u) from the input string using StringBuilder .
3) AppendToWords: Use StringBuilder to append a specified character at the start and end of each word in a sentence.
4) ReplaceWord: Implement logic to replace all occurrences of a specific word in the input string with another word using StringBuilder .

using System;
using System.Text;
Boiler Plate Code:--
public class StringBuilderOperations
{

// Function to reverse a string using StringBuilder


public static string ReverseString(string input)
{
// Implement logic here
return string.Empty;
}

// Function to remove all vowels from a string using StringBuilder


public static string RemoveVowels(string input)
{
// Implement logic here
return string.Empty;
}

// Function to append a specified character at the start and end of each word in a sentence
public static string AppendToWords(string input, char toAppend)
{
// Implement logic here
return string.Empty;
}

// Function to replace all occurrences of a specific word in a string with another word using StringBuilder
public static string ReplaceWord(string input, string targetWord, string replacementWord)
{
// Implement logic here
return string.Empty;
}

// Main method for testing


public static void Main(string[] args)
{
string testString = "StringBuilder is powerful";

Console.WriteLine("Reversed String: " + ReverseString(testString));


Console.WriteLine("String Without Vowels: " + RemoveVowels(testString));
Console.WriteLine("Appended to Words: " + AppendToWords(testString, '*'));
Console.WriteLine("Replace 'powerful' with 'amazing': " + ReplaceWord(testString, "powerful", "amazing"));
}
}
using System;
using System.Text;

public class StringBuilderOperations


{
// Function to reverse a string using StringBuilder
Actual Answer
public static string ReverseString(string input)
{
StringBuilder reversed = new StringBuilder();
for (int i = input.Length - 1; i >= 0; i--)
{
reversed.Append(input[i]);
}
return reversed.ToString();
}

// Function to remove all vowels from a string using StringBuilder


public static string RemoveVowels(string input)
{
StringBuilder result = new StringBuilder();
foreach (char c in input)
{
if (!"aeiouAEIOU".Contains(c))
{
result.Append(c);
}
}
return result.ToString();
}

// Function to append a specified character at the start and end of each word in a sentence
public static string AppendToWords(string input, char toAppend)
{
StringBuilder result = new StringBuilder();
string[] words = input.Split(' ');
foreach (string word in words)
{
result.Append(toAppend).Append(word).Append(toAppend).Append(' ');
}
return result.ToString().TrimEnd();
}

// Function to replace all occurrences of a specific word in a string with another word using StringBuilder
public static string ReplaceWord(string input, string targetWord, string replacementWord)
{
StringBuilder result = new StringBuilder();
string[] words = input.Split(' ');
foreach (string word in words)
{
if (word.Equals(targetWord))
{
result.Append(replacementWord);
}
else
{
result.Append(word);
}
result.Append(' ');
}
return result.ToString().TrimEnd();
}

// Main method for testing


public static void Main(string[] args)
{
string testString = "StringBuilder is powerful";
Console.WriteLine("Reversed String: " + ReverseString(testString));
Console.WriteLine("String Without Vowels: " + RemoveVowels(testString));
Console.WriteLine("Appended to Words: " + AppendToWords(testString, '*'));
Console.WriteLine("Replace 'powerful' with 'amazing': " + ReplaceWord(testString, "powerful", "amazing"));
}
}
No need to give input if ask give this
Input:-

"StringBuilder is powerful"

Output:-

Reversed String: lufrewop si redliuBgnirtS


String Without Vowels: StrngBldr s pwrfl
Appended to Words: *StringBuilder* *is* *powerful*
Replace 'powerful' with 'amazing': StringBuilder is amazing
Question 13
Implement the missing logic for the given Code

Task to implement.
1) ReverseWords: Write logic to reverse every word in the input sentence while keeping the words in order.
2) RemoveVowels: Implement logic to remove all vowels from the input string using StringBuilder .
3) ReplaceEveryNthCharacter: Write logic to replace every nth character in the input string with a specified character.
4) GeneratePalindrome: Implement logic to generate a palindrome by appending the reverse of the input string to itself..

using System;
using System.Text;
--------------- Boiler Plate Code:--

public class StringBuilderOperations


{
// Function to reverse every word in a sentence using StringBuilder
public static string ReverseWords(StringBuilder input)
{
// Implement logic here
return string.Empty;
}

// Function to remove all vowels from a string using StringBuilder


public static string RemoveVowels(StringBuilder input)
{
// Implement logic here
return string.Empty;
}

// Function to replace every nth character in a string with a specific character using StringBuilder
public static string ReplaceEveryNthCharacter(StringBuilder input, char replacement, int n)
{
// Implement logic here
return string.Empty;
}

// Function to generate a palindrome from a string using StringBuilder


public static string GeneratePalindrome(StringBuilder input)
{
// Implement logic here
return string.Empty;
}

// Main method for testing


public static void Main(string[] args)
{
StringBuilder testInput = new StringBuilder("hello world from csharp");

Console.WriteLine("Reversed Words: " + ReverseWords(testInput));


Console.WriteLine("Without Vowels: " + RemoveVowels(testInput));
Console.WriteLine("Replace Every 3rd Character with '*': " + ReplaceEveryNthCharacter(testInput, '*', 3));
Console.WriteLine("Generated Palindrome: " + GeneratePalindrome(new StringBuilder("race")));
}
}
using System;
using System.Text;
using System.Linq; // Make sure this namespace is included for LINQ operations

public class StringBuilderOperations


{
Actual Answer
// Function to reverse every word in a sentence using StringBuilder
public static string ReverseWords(StringBuilder input)
{
string[] words = input.ToString().Split(' ');
for (int i = 0; i < words.Length; i++)
{
char[] wordArray = words[i].ToCharArray();
Array.Reverse(wordArray);
words[i] = new string(wordArray);
}
return string.Join(" ", words);
}

// Function to remove all vowels from a string using StringBuilder


public static string RemoveVowels(StringBuilder input)
{
StringBuilder result = new StringBuilder();
string vowels = "aeiouAEIOU";
foreach (char c in input.ToString())
{
if (!vowels.Contains(c))
{
result.Append(c);
}
}
return result.ToString();
}

// Function to replace every nth character in a string with a specific character using StringBuilder
public static string ReplaceEveryNthCharacter(StringBuilder input, char replacement, int n)
{
for (int i = n - 1; i < input.Length; i += n)
{
input[i] = replacement;
}
return input.ToString();
}

// Function to generate a palindrome from a string using StringBuilder


public static string GeneratePalindrome(StringBuilder input)
{
// Convert StringBuilder to string, then to char array, reverse it, and convert back to string
string reversed = new string(input.ToString().ToCharArray().Reverse().ToArray());
return input.ToString() + reversed;
}

// Main method for testing


public static void Main(string[] args)
{
StringBuilder testInput = new StringBuilder("hello world from csharp");
Console.WriteLine("Reversed Words: " + ReverseWords(testInput));
Console.WriteLine("Without Vowels: " + RemoveVowels(testInput));
Console.WriteLine("Replace Every 3rd Character with '*': " + ReplaceEveryNthCharacter(testInput, '*', 3));
Console.WriteLine("Generated Palindrome: " + GeneratePalindrome(new StringBuilder("race")));
}
}
No need to give input if ask give this
Input:-

Output:-

Reversed Words: olleh dlrow morf prahsc


Without Vowels: hll wrld frm cshrp
Replace Every 3rd Character with '*': he*lo*wo*ld*fr*m *sh*rp
Generated Palindrome: raceecar
Question 14
Implement the missing logic for the given Code

Task to implement..
1) InsertAfterEachWord: Write logic to insert a specific substring after each word in the sentence using StringBuilder .
2) CountCharacterFrequency: Implement logic to count the frequency of a specific character in the string using StringBuilder .
3) ReplaceSubstring: Write logic to replace all occurrences of one substring with another in the input using StringBuilder .
4) CompressString: Implement logic to remove all spaces from the string and return the compressed version using StringBuilder

using System;
using System.Text; Boiler Plate Code:--
public class AdvancedStringBuilderOperations
{
// Function to insert a specific substring after every word in a sentence
public static string InsertAfterEachWord(StringBuilder input, string toInsert)
{
// Implement logic here
return string.Empty;
}

// Function to count the frequency of a specific character in the string


public static int CountCharacterFrequency(StringBuilder input, char target)
{
// Implement logic here
return 0;
}

// Function to replace all occurrences of a substring with another substring


public static string ReplaceSubstring(StringBuilder input, string oldValue, string newValue)
{
// Implement logic here
return string.Empty;
}

// Function to remove all spaces and compress the string using StringBuilder
public static string CompressString(StringBuilder input)
{
// Implement logic here
return string.Empty;
}

// Main method for testing


public static void Main(string[] args)
{
StringBuilder testInput = new StringBuilder("hello world from csharp hello");

Console.WriteLine("Insert After Each Word: " + InsertAfterEachWord(testInput, "-inserted"));


Console.WriteLine("Frequency of 'o': " + CountCharacterFrequency(testInput, 'o'));
Console.WriteLine("Replace 'hello' with 'hi': " + ReplaceSubstring(testInput, "hello", "hi"));
Console.WriteLine("Compressed String: " + CompressString(testInput));
}
}
using System;
using System.Text;

public class AdvancedStringBuilderOperations


{
// Function to insert a specific substring after every word in a sentence Actual Answer
public static string InsertAfterEachWord(StringBuilder input, string toInsert)
{
StringBuilder result = new StringBuilder();
string[] words = input.ToString().Split(' ');

foreach (string word in words)


{
result.Append(word + toInsert + " ");
}

return result.ToString().Trim();
}

// Function to count the frequency of a specific character in the string


public static int CountCharacterFrequency(StringBuilder input, char target)
{
int frequency = 0;

foreach (char c in input.ToString())


{
if (c == target)
frequency++;
}

return frequency;
}

// Function to replace all occurrences of a substring with another substring


public static string ReplaceSubstring(StringBuilder input, string oldValue, string newValue)
{
return input.ToString().Replace(oldValue, newValue);
}

// Function to remove all spaces and compress the string using StringBuilder
public static string CompressString(StringBuilder input)
{
StringBuilder result = new StringBuilder();

foreach (char c in input.ToString())


{
if (c != ' ')
{
result.Append(c);
}
}

return result.ToString();
}

// Main method for testing


public static void Main(string[] args)
{
StringBuilder testInput = new StringBuilder("hello world from csharp hello");

Console.WriteLine("Insert After Each Word: " + InsertAfterEachWord(testInput, "-inserted"));


Console.WriteLine("Frequency of 'o': " + CountCharacterFrequency(testInput, 'o'));
Console.WriteLine("Replace 'hello' with 'hi': " + ReplaceSubstring(testInput, "hello", "hi"));
Console.WriteLine("Compressed String: " + CompressString(testInput));
}
}
No need to give input if ask give this
Input:-

Output:-

Insert After Each Word: hello-inserted world-inserted from-inserted


csharp-inserted hello-inserted
Frequency of 'o': 4
Replace 'hello' with 'hi': hi world from csharp hi
Compressed String: helloworldfromcsharphello
Question 15
Implement the missing logic for the given Code

Task to implement..
1) ExtractWordsStartingWith: Write logic to split the input sentence into words and extract all words that start with a specific character using Split and
Substring .
2) FindAllIndicesOfSubstring: Implement logic to find and return all starting indices of a given substring in the input string using IndexOf .
3) AllWordsContainCharacter: Write logic to check if every word in the input string contains a specific character using Contains .
4) ReplaceWordsContainingSubstring: Implement logic to replace all words containing a given substring with a specified replacement word.

using System;
---------- Boiler Plate Code:--
public class StringFunctionOperations
{
// Function to extract all words starting with a specific character using Split and Substring
public static string[] ExtractWordsStartingWith(string input, char startingChar)
{
// Implement logic here
return new string[0];
}

// Function to find all indices of a substring in a string


public static int[] FindAllIndicesOfSubstring(string input, string substring)
{
// Implement logic here
return new int[0];
}

// Function to check if all words in a sentence contain a specific character


public static bool AllWordsContainCharacter(string input, char targetChar)
{
// Implement logic here
return false;
}

// Function to replace all words containing a specific substring with another word
public static string ReplaceWordsContainingSubstring(string input, string substring, string replacement)
{
// Implement logic here
return string.Empty;
}

// Main method for testing


public static void Main(string[] args)
{
string testString = "hello world from C# programming language";

Console.WriteLine("Words Starting with 'h': " + string.Join(", ", ExtractWordsStartingWith(testString, 'h')));


Console.WriteLine("Indices of 'world': " + string.Join(", ", FindAllIndicesOfSubstring(testString, "world")));
Console.WriteLine("All Words Contain 'o': " + AllWordsContainCharacter(testString, 'o'));
Console.WriteLine("Replace Words Containing 'pro': " + ReplaceWordsContainingSubstring(testString, "pro", "awesome"));
}
}
using System;
using System.Collections.Generic;

public class StringFunctionOperations


{
// Function to extract all words starting with a specific character using Split and Substring
public static string[] ExtractWordsStartingWith(string input, char startingChar)
Actual Answer
{
// Split the input string into words
string[] words = input.Split(' ');
List<string> result = new List<string>();

// Iterate over each word and check if it starts with the given character
foreach (string word in words)
{
if (word.Length > 0 && word[0] == startingChar)
{
result.Add(word);
}
}
return result.ToArray();
}

// Function to find all indices of a substring in a string


public static int[] FindAllIndicesOfSubstring(string input, string substring)
{
List<int> indices = new List<int>();
int index = input.IndexOf(substring);

// Keep finding the next index of the substring until no more are found
while (index != -1)
{
indices.Add(index);
index = input.IndexOf(substring, index + 1);
}
return indices.ToArray();
}

// Function to check if all words in a sentence contain a specific character


public static bool AllWordsContainCharacter(string input, char targetChar)
{
string[] words = input.Split(' ');

// Check if every word contains the specified character


foreach (string word in words)
{
if (!word.Contains(targetChar))
{
return false;
}
}
return true;
}

// Function to replace all words containing a specific substring with another word
public static string ReplaceWordsContainingSubstring(string input, string substring, string replacement)
{
string[] words = input.Split(' ');
List<string> result = new List<string>();

// Replace words containing the substring with the replacement


foreach (string word in words)
{
if (word.Contains(substring))
{
result.Add(replacement);
}
else
{
result.Add(word);
}
}
return string.Join(" ", result);
}

// Main method for testing


public static void Main(string[] args)
{
string testString = "hello world from C# programming language";

Console.WriteLine("Words Starting with 'h': " + string.Join(", ", ExtractWordsStartingWith(testString, 'h')));


Console.WriteLine("Indices of 'world': " + string.Join(", ", FindAllIndicesOfSubstring(testString, "world")));
Console.WriteLine("All Words Contain 'o': " + AllWordsContainCharacter(testString, 'o'));
Console.WriteLine("Replace Words Containing 'pro': " + ReplaceWordsContainingSubstring(testString, "pro", "awesome"));
}
}
No need to give input if ask give this
Input:-

Output:-

Words Starting with 'h': hello


Indices of 'world': 6
All Words Contain 'o': False
Replace Words Containing 'pro': hello world from C# awesome language

You might also like