C# String
C# String
C# String methods
2. Write a program in C# Sharp to find the length of a string without using library function.
using System;
public class Exercise2
{
public static void Main()
{
string str; /* Declares a string of size 100 */
int l= 0;
Console.Write("\n\nFind the length of a string :\n");
Console.Write("---------------------------------\n");
Console.Write("Input the string : ");
str = Console.ReadLine();
foreach(char chr in str)
{
l += 1;
}
Console.Write("Length of the string is : {0}\n\n", l);
}
}
4. Write a program in C# Sharp to print individual characters of the string in reverse order.
using System;
public class Exercise4
{
public static void Main()
{
string str;
int l=0;
Console.Write("\n\nprint individual characters of string in reverse order :\n");
Console.Write("------------------------------------------------------\n");
Console.Write("Input the string : ");
str = Console.ReadLine();
l = str.Length - 1;
Console.Write("The characters of the string in reverse are : \n");
while (l >= 0)
{
Console.Write("{0} ", str[l]);
l--;
}
Console.Write("\n\n");
}
}
l++;
}
6. Write a program in C# Sharp to compare two string without using string library functions.
using System;
public class Exercise6
{
public static void Main()
{
string str1, str2;
int flg=0;
int i=0,l1,l2,yn=0;
Console.Write("\n\nCompare two string whether they are equal or not :\n");
Console.Write("------------------------------------------------------\n");
Console.Write("Input the 1st string : ");
str1 = Console.ReadLine();
Console.Write("Input the 2nd string : ");
str2 = Console.ReadLine();
l1=str1.Length;
l2=str2.Length;
/*compare checking when they are equal in length*/
if(l1==l2)
{
for(i=0;i<l1;i++)
{
if(str1[i] != str2[i])
{
yn=1;
i=l1;
}
}
}
Subrat Kumar Dash(IT Faculty), Mob: 7978718584 5|P a ge
C# Programs on String C-Net
/*initialize the flage where they are equal, smaller and greater in length*/
if(l1 == l2)
flg=0;
else if(l1 > l2)
flg=1;
else if(l1 < l2)
flg=-1;
/*display the message where the strings are same or smaller or greater*/
if(flg == 0)
{
if(yn==0)
Console.Write("\nThe length of both strings are equal and \nalso, both strings are same.\n\n");
else
Console.Write("\nThe length of both strings are equal \nbut they are not same.\n\n");
}
else if(flg == -1)
{
Console.Write("\nThe length of the first string is smaller than second.\n\n");
}
else
{
Console.Write("\nThe length of the first string is greater than second.\n\n");
}
}
}
7. Write a program in C# Sharp to count a total number of alphabets, digits and special characters
in a string.
using System;
public class Exercise7
{
public static void Main()
{
string str;
int alp, digit, splch, i,l;
alp = digit = splch = i = 0;
Console.Write("\n\nCount total number of alphabets, digits and special characters :\n");
Console.Write("--------------------------------------------------------------------\n");
Console.Write("Input the string : ");
str = Console.ReadLine();
l=str.Length;
/* Checks each character of string*/
while(i<l)
{
if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
{
alp++;
}
Subrat Kumar Dash(IT Faculty), Mob: 7978718584 6|P a ge
C# Programs on String C-Net
else if(str[i]>='0' && str[i]<='9')
{
digit++;
}
else
{
splch++;
}
i++;
}
l=str1.Length;
string[] str2=new string[l];
i++;
}
// Console.Write("{0} ",(char)65);
max = 0;
for(i=0; i<255; i++)
{
if(i!=32)
{
if(ch_fre[i] > ch_fre[max])
max = i;
}
}
Console.Write("The Highest frequency of character '{0}' is appearing for number of times : {1} \n\n",
(char)max, ch_fre[max]);
}
}
for(i=1;i<l;i++)
for(j=0;j<l-i;j++)
if(arr1[j]>arr1[j+1])
{
ch=arr1[j];
arr1[j] = arr1[j+1];
arr1[j+1]=ch;
}
Console.Write("After sorting the string appears like : \n");
foreach (char c in arr1)
{
ch=c;
Console.Write("{0} ",ch);
}
Console.WriteLine("\n");
}
}
12. Write a program in C# Sharp to read a string through the keyboard and sort it using bubble
sort.
using System;
public class exercise12
{
public static void Main()
{
string[] arr1;
string temp;
int n,i,j,l;
13. Write a program in C# Sharp to extract a substring from a given string without using the
library function.
using System;
public class exercise13
{
public static void Main()
{
string str;
char[] arr1;
int pos, l, ln, c = 0;
14. Write a C# Sharp program to check whether a given substring is present in the given string
using System;
public class exercise14
{
public static void Main()
{
string str1,str2;
bool m;
15. Write a program in C# Sharp to read a sentence and replace lowercase characters by
uppercase and vice-versa.
using System;
public class exercise15
{
public static void Main()
{
string str1;
char[] arr1;
int l,i;
l=0;
char ch;
Console.Write("\n\nReplace lowercase characters by uppercase and vice-versa :\n");
Console.Write("--------------------------------------------------------------\n");
Console.Write("Input the string : ");
str1 = Console.ReadLine();
l=str1.Length;
arr1 = str1.ToCharArray(0, l); // Converts string into char array.
do
{
Console.Write("Input a username: ");
username = Console.ReadLine();
}
while((username != "abcd" || password != "1234") && (ctr != 3));
if (ctr == 3)
Console.Write("\nLogin attemp three or more times. Try later!\n\n");
else
Console.Write("\nThe password entered successfully!\n\n");
}
}
17. Write a program in C# Sharp to search the position of a substring within a string.
string str1;
string findstr;
Console.Write("\n\nSearch the position of a substing within a string :\n");
Console.Write("-------------------------------------------------------\n");
Console.Write("Input a String: ");
str1 = Console.ReadLine();
18. Write a program in C# Sharp to check whether a character is an alphabet and not and if so, go
to check for the case.
using System;
public class Exercise18
{
static void Main()
{
Console.Write("\n\nCheck whether a character is alphabet or not and if so, check for case :\n");
Console.Write("-----------------------------------------------------------------------------\n");
Console.Write("Input a character: ");
char ch = (char)Console.Read();
if (Char.IsLetter(ch))
{
if (Char.IsUpper(ch))
{
Console.WriteLine("\nThe character is uppercase.\n");
}
else
{
Console.WriteLine("\nThe character is lowercase.\n");
}
}
else
Subrat Kumar Dash(IT Faculty), Mob: 7978718584 14 | P a g e
C# Programs on String C-Net
{
Console.WriteLine("\nThe entered character is not an alphabetic character.\n");
}
}
}
19. Write a program in C# Sharp to find the number of times a substring appears in the given
string.
using System;
public class exercise19
{
public static void Main()
{
string str1;
string findstring;
int strt = 0;
int cnt = -1;
int idx = -1;
20. Write a program in C# Sharp to insert a substring before the first occurrence of a string.
using System;
public class Exercise20
{
public static void Main()
{
string str1;
string findstring;
string insertstring;
Subrat Kumar Dash(IT Faculty), Mob: 7978718584 15 | P a g e
C# Programs on String C-Net
int i;
21. Write a C# Sharp program to compare (less than, greater than, equal to ) two substrings.
// Example for String.Compare(String, Int32, String, Int32, Int32)
using System;
class Example21
{
public static void Main() {
// 01234567
String str1 = "computer";
String str2 = "system";
String str;
int result;
Console.WriteLine();
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
result = String.Compare(str1, 2, str2, 0, 2);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(0, 2), str2);
}
}
22. Write a C# Sharp program to compare two substrings that only differ in case. The first
comparison ignores case and the second comparison considers case.
using System;
class Example22
{
public static void Main() {
Subrat Kumar Dash(IT Faculty), Mob: 7978718584 16 | P a g e
C# Programs on String C-Net
// 01234567
String str1 = "COMPUTER";
String str2 = "computer";
String str;
int result;
Console.WriteLine();
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
Console.WriteLine("Ignore case:");
result = String.Compare(str1, 2, str2, 2, 2, true);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(2, 2), str2);
Console.WriteLine();
Console.WriteLine("Honor case:");
result = String.Compare(str1, 2, str2, 2, 2, false);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(2, 2), str2);
}
}
23. Write a C# Sharp program to compare two substrings using different cultures and ignoring the
case of the substrings.
// Example for String.Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)
using System;
using System.Globalization;
class Example23 {
public static void Main() {
// 01234567
String str1 = "COMPUTER";
String str2 = "computer";
String str;
int result;
Console.WriteLine();
Console.WriteLine("\n str1 = '{0}', str2 = '{1}'", str1, str2);
Console.WriteLine("Ignore case, Turkish culture:");
result = String.Compare(str1, 4, str2, 4, 2, true, new CultureInfo("tr-TR"));
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(4, 2), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(4, 2), str2);
24. Write a C# Sharp program to compare the last names of two people. It then lists them in
alphabetical order.
using System;
using System.Globalization;
25. Write a C# Sharp program to compares four sets of words by using each member of the
StringComparison enumeration.
The comparisons use the conventions of the English (United States) and Sami (Upper Sweden) cultures.
Note: that the strings "encyclopedia" and "encyclopedia" are considered equivalent in the en-US culture
but not in the Sami (Northern Sweden) culture.
using System;
using System.Globalization;
using System.Threading;
Subrat Kumar Dash(IT Faculty), Mob: 7978718584 18 | P a g e
C# Programs on String C-Net
Console.WriteLine();
}
Console.WriteLine();
}
}
}
26. Write C# Sharp program to demonstrate that the Compare(String, String, Boolean) method is
equivalent to using ToUpper or ToLower when comparing strings.
using System;
class Example26
{
static void Main()
{
// Create upper-case characters from their Unicode code units.
String stringUpper = "\x0051\x0052\x0053";
// The previous method call is equivalent to this Compare method, which ignores case.
Console.WriteLine("The Strings are equal when case is ignored? {0}",
String.Compare(stringUpper, stringLower, true) == 0
? "true" : "false" );
}
}
27. Write a C# Sharp program to demonstrate how culture can affect a comparison.
Note : In Czech – Czech Republic culture, "ch" is a single character that is greater than "d". However, in
English - United States culture, "ch" consists of two characters, and "c" is less than "d".
using System;
using System.Globalization;
class Example27
{
public static void Main() {
String str1 = "change";
String str2 = "dollar";
String relation = null;
28. Write a C# Sharp program to compare two strings in following three different ways produce
three different results.
a. using linguistic comparison for the en-US culture.
b. using linguistic case-sensitive comparison for the en-US culture.
c. using an ordinal comparison. It illustrates how the three methods of comparison.
using System;
using System.Globalization;
class Example30
{
public static void Main(String[] args)
{
String strLow = "xyz";
String strCap = "XYZ";
String result = "equal to ";
int x = 0;
int pos = 1;
// The Unicode codepoint for 'b' is greater than the codepoint for 'B'.
x = String.CompareOrdinal(strLow, pos, strCap, pos, 1);
if (x < 0) result = "less than";
if (x > 0) result = "greater than";
Console.WriteLine("CompareOrdinal(\"{0}\"[{2}], \"{1}\"[{2}]):", strLow, strCap, pos);
Console.WriteLine(" '{0}' is {1} '{2}'", strLow[pos], result, strCap[pos]);
30. Write a C# Sharp program to concatenate three objects, objects with a variable and 3-element
object array.
using System;
class Example34
{
public static void Main() {
int i = -123;
Object o = i;
Object[] objs = new Object[] {-123, -456, -789};
32. Write a C# Sharp program to determine whether the string "birds" is a substring of a familiar.
class Example38
{
public static void Main()
{
string str1 = "Kill two birds with one stone";
string str2 = "birds";
bool x = str1.Contains(str2);
Console.WriteLine("'{0}' is in the string '{1}': {2}",
str2, str1, x);
if (x) {
int index = str1.IndexOf(str2);
if (index >= 0)
Console.WriteLine("'{0} begins at character position {1}",
str2, index + 1);
}
}
}
Subrat Kumar Dash(IT Faculty), Mob: 7978718584 23 | P a g e
C# Programs on String C-Net
33. Write a C# Sharp program to indicate whether each string in an array ends with a period (".").
using System;
34. Write C# Sharp program to check whether a string occurs at the end of another string.
using System;
using System.Threading;
using System.Globalization;
class Example42
{
public static void Main()
{
string str1 = "Search for the target string \"{0}\" in the string \"{1}\".\n";
string str2 = "Using the {0} - \"{1}\" culture:";
string str3 = " The string to search ends with the target string: {0}";
bool result = false;
CultureInfo ci;
Console.WriteLine("Case sensitive:");
result = abcARing.EndsWith(capitalARing, false, ci);
Console.WriteLine(str3, result);
Console.WriteLine("Case insensitive:");
result = abcARing.EndsWith(capitalARing, true, ci);
Console.WriteLine(str3, result);
Console.WriteLine();
Console.WriteLine("Case sensitive:");
result = abcARing.EndsWith(capitalARing, false, ci);
Console.WriteLine(str3, result);
Console.WriteLine("Case insensitive:");
result = abcARing.EndsWith(capitalARing, true, ci);
Console.WriteLine(str3, result);
}
}
35. Write a C# Sharp program to determine whether a string ends with a particular substring.
The results are affected by the choice of culture, whether case is ignored, and whether an ordinal
comparison is performed.
using System;
using System.Threading;
class Example43
{
public static void Main()
{
string str = "Determine whether a string ends with another string, " +
"using\n different values of StringComparison.";
StringComparison[] scValues = {
StringComparison.CurrentCulture,
StringComparison.CurrentCultureIgnoreCase,
StringComparison.InvariantCulture,
StringComparison.InvariantCultureIgnoreCase,
StringComparison.Ordinal,
Subrat Kumar Dash(IT Faculty), Mob: 7978718584 25 | P a g e
C# Programs on String C-Net
StringComparison.OrdinalIgnoreCase };
//
Console.Clear();
Console.WriteLine(str);
// Determine whether three versions of the letter I are equal to each other.
foreach (StringComparison sc in scValues)
{
Console.WriteLine("StringComparison.{0}:", sc);
Test("xyzPQR", "PQR", sc);
Test("xyzPQR", "PQR", sc);
Console.WriteLine();
}
}