Course Title – Programming With Object Laboratory(AITD02)
Topic Title –week-3- Strings Manipulations
Presenter’s Name – Mr. Somla
Presenter’s ID – IARE11027
Department Name – CSE (Artificial Intelligence and Machine Learning)
Lecture Number - 01
Presentation Date – 28.08.2025
COURSE OUTCOMES:
Week-3 Strings Manipulations
String manipulation refers to the process of modifying, analyzing, or transforming strings,
which are sequences of characters. It is a fundamental aspect of programming across
various languages and is used for tasks involving text data.
Common string manipulation operations include:
Concatenation: Joining two or more strings together to form a new, longer string.
Substring Extraction: Obtaining a portion of a string based on specific starting and
ending positions, or by searching for patterns.
Searching and Replacing: Finding occurrences of specific characters or patterns
within a string and replacing them with other characters or patterns.
Case Conversion: Changing the case of characters within a string (e.g., converting to
uppercase or lowercase).
Trimming/Padding: Removing leading or trailing whitespace from a string, or adding
characters to the beginning or end to reach a desired length.
Splitting: Dividing a string into an array or list of smaller strings based on a delimiter
character or pattern.
Length Calculation: Determining the number of characters in a string.
Comparison: Comparing two strings to check for equality or lexicographical order.
Many programming languages provide built-in functions or methods for performing these
and other string manipulation tasks, simplifying the process for developers. Examples
include C#'s string methods, Java's String class methods, and C# string functions. Efficient
string manipulation is crucial for various applications, including data processing, text
analysis, user input handling, and more.
3.1 Find the Bomb
Create a function that finds the word “bomb” in the given string (not case sensitive). If found,
return “Duck!!!”, otherwise, return “There is no bomb, relax.”.
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(BombDetector("This is a Bomb example")); // Output: Duck!!!
Console.WriteLine(BombDetector("Everything is safe here")); // Output: There is no
bomb, relax.
}
static string BombDetector(string input)
{
if (input.ToLower().Contains("bomb"))
{
return "Duck!!!";
}
else
{
return "There is no bomb, relax.";
}
}
}
Output:
Duck!!!
There is no bomb, relax.
3.2 Finding Nemo
Finding Nemo You’re given a string of words. You need to find the word “Nemo”, and return a
string like this:
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(FindNemo("I am finding Nemo !")); // Output: I found Nemo at 4!
Console.WriteLine(FindNemo("Nemo is hiding")); // Output: I found Nemo at 1!
Console.WriteLine(FindNemo("There is no fish here")); // Output: I can't find Nemo :(
}
static string FindNemo(string sentence)
{
string[] words = sentence.Split(' ', StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < words.Length; i++)
{
// Remove punctuation if attached (like "Nemo!" or "Nemo,")
string cleanWord = words[i].Trim('!', '.', ',', '?');
if (cleanWord.Equals("Nemo", StringComparison.OrdinalIgnoreCase))
{
return $"I found Nemo at {i + 1}!";
}
}
return "I can't find Nemo :(";
}
}
Output:
I found Nemo at 4!
I found Nemo at 1!
I can't find Nemo :(
3.3 A Week Later
Create a function which takes in a date as a string, and returns the date a week after.
Program:
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetDateAfterWeek("2025-08-20")); // Output: 2025-08-27
Console.WriteLine(GetDateAfterWeek("12/25/2025")); // Output: 01/01/2026
}
static string GetDateAfterWeek(string dateStr)
{
if (DateTime.TryParse(dateStr, out DateTime date))
{
DateTime nextWeek = date.AddDays(7);
return nextWeek.ToString("yyyy-MM-dd"); // Format output as YYYY-MM-DD
}
else
{
return "Invalid date format";
}
}
}
Output:
2025-08-27
2026-01-01
3.4 Track the Robot
using System;
class Program
{
static void Main(string[] args)
{
string[] moves = { "right 10", "up 50", "left 30", "down 10" };
int[] result = FinalPosition(moves);
Console.WriteLine($"[{result[0]}, {result[1]}]"); // Output: [-20, 40]
}
static int[] FinalPosition(string[] moves)
{
int x = 0, y = 0; // Starting at [0, 0]
foreach (string move in moves)
{
string[] parts =
Output:
error
3.5 True Alphabetical Order
Create a function which takes every letter in every word, and puts it in alphabetical order.
Note how the original word lengths must stay the same.
Program:
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(SortLettersInWords("hello world"));
// Output: "ehllo dlorw"
Console.WriteLine(SortLettersInWords("programming is fun"));
// Output: "aggimmnoprr is fnu"
}
static string SortLettersInWords(string sentence)
{
string[] words = sentence.Split(' ', StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < words.Length; i++)
{
words[i] = new string(words[i].OrderBy(c => c).ToArray());
return string.Join(" ", words);
}
}Output:
ehllo dlorw
aggimmnoprr is fnu
3.6 Longest Common Ending
Create a function which takes every letter in every word, and puts it in alphabetical order.
Note how the original word lengths must stay the same.
Program:
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(SortLettersAcrossWords("hello world"));
// Output: "dehllloorw" distributed -> "dehll oloorw"
Console.WriteLine(SortLettersAcrossWords("programming is fun"));
// Example output depends on redistribution
}
static string SortLettersAcrossWords(string sentence)
{
// Remove spaces and collect all characters
List<char> allChars = sentence.Replace(" ", "").ToList();
// Sort all characters alphabetically
allChars.Sort();
// Split sentence into words (to know lengths)
string[] words = sentence.Split(' ', StringSplitOptions.RemoveEmptyEntries);
List<string> resultWords = new List<string>();
int index = 0;
// Reconstruct words with same lengths
foreach (string word in words)
{
int length = word.Length;
string newWord = new string(allChars.Skip(index).Take(length).ToArray());
resultWords.Add(newWord);
index += length;
return string.Join(" ", resultWords);
}
}
Output:
dehll loorw
afggiimmnno pr rsu
3.6 Longest Common Ending
Write a function that returns the longest common ending between two strings.
Program
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(LongestCommonEnding("walking", "jogging")); // "ing"
Console.WriteLine(LongestCommonEnding("nation", "station")); // "ation"
Console.WriteLine(LongestCommonEnding("hello", "world")); // ""
}
static string LongestCommonEnding(string str1, string str2)
{
int i = str1.Length - 1;
int j = str2.Length - 1;
string common = "";
// Compare characters from the end
while (i >= 0 && j >= 0 && str1[i] == str2[j])
{
common = str1[i] + common; // prepend matched char
i--;
j--;
}
return common;
}
}
Output:
ing
ation
3.7 Clear Brackets
Create a function Brackets() that takes a string and checks that the brackets in the math
expression are correct. The function should return true or false.
Program
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Brackets("(2+3)*(5-2)")); // true
Console.WriteLine(Brackets("((2+3)")); // false
Console.WriteLine(Brackets("2+3)*5")); // false
Console.WriteLine(Brackets("((2+3)*(4-1))")); // true
}
static bool Brackets(string expr)
{
int balance = 0;
foreach (char ch in expr)
{
if (ch == '(') balance++;
else if (ch == ')')
{
balance--;
if (balance < 0) return false; // more ')' than '('
}
}
return balance == 0; // must be balanced
}
}
Output:
True
False
False
True
3.8 Count the Number of Duplicate Characters
Create a function that takes a string and returns the number of alphanumeric characters that
occur more than once.
Program:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(CountDuplicates("hello123321")); // 4 (h=0, e=0, l=2, o=0, 1=2, 2=2,
3=2)
Console.WriteLine(CountDuplicates("abcABC123")); // 0
Console.WriteLine(CountDuplicates("aabbccdd11")); // 5
static int CountDuplicates(string input)
{
Dictionary<char, int> co
Output:
ERROR!
/tmp/eNlfh8835J/Main.cs(16,33): error CS1002: ; expected
/tmp/eNlfh8835J/Main.cs(16,33): error CS1513: } expected
3.9 Uban Numbers
A number n is called uban if its name (in English) does not contain the letter “u”. In
particular, it cannot contain the terms “four”, “hundred”, and “thousand”, so the uban
number following 99 is 1,000,000. Write a function to determine if the given integer is uban.
Program:
using System;
using System.Globalization;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(IsUban(10)); // true ("ten")
Console.WriteLine(IsUban(4)); // false ("four")
Console.WriteLine(IsUban(99)); // true ("ninety-nine")
Console.WriteLine(IsUban(100)); // false ("one hundred")
Console.WriteLine(IsUban(1000000)); // true ("one million")
}
static bool IsUban(int n)
{
// Convert number to words in English
string words = NumberToWords(n);
// Check if it contains 'u'
return !words.ToLower().Contains("u");
}
// Helper function to convert number to English words
static string NumberToWords(int number)
{
if (number == 0)
return "zero";
if (number < 0)
return "minus " + NumberToWords(Math.Abs(number));
string words = "";
if ((number / 1000000) > 0)
{
words += NumberToWords(number / 1000000) + " million ";
number %= 1000000;
}
if ((number / 1000) > 0)
{
words += NumberToWords(number / 1000) + " thousand ";
number %= 1000;
if ((number / 100) > 0)
{
words += NumberToWords(numb
output:
try to run and execute and get output