String Extraction And Insertion In C#
| The following is the class that replaces one string with another stringspecified by the user. Just as in Java or any other language,C#(C-Sharp) also has string manipulators but since we are talking aboutoriginal pieces of codes, I have written the following piece oforiginal method called getstr–which gets a string from another throughan object of the 'string' class ! Java's string class has an uniquebehaviour, in that it takes strings into constructors and thenmanipulates and gives the result. Only an experienced OOPS programmercan tackle string manipulation in Java. But in C#, string manipulationis as easy as it has always been in C++. Just use objects of stringclass and extract, one by one, each character from the object into a'char' variable just as if you were using an array ! Simple.
Another interesting aspect in the "getstr"method is that it suppresses the system error"ArgumentOutOfRangeException" by 'catch'-ing it into the 'e' object anddisplays your own error message. Of course, another way of stringmanipulation is through the class indexers – the unique feature of C#which allows access to the class members as if they were arrays and notobjects ! My next code example will concentrate on "Class Indexers – it is different from properties !" |
class replacestr{
string s,s2,s4;
char s1,s3,s5,newchar,err=' ';
public void getstr(){
System.Console.Write("Please enter a string ");
try{
s=System.Console.ReadLine();
System.Console.Write("Please enter character in string to be replaced ");
s4=System.Console.ReadLine();
System.Console.Write("Please enter the character to be replaced with ");
s2=System.Console.ReadLine();
}
catch (System.ArgumentOutOfRangeException a){
System.Console.Write("Please enter some value or press space bar for space{1}",a,err);
}
s5=s2[0];
s1=s4[0];
try{
for (int i=0;i<6;i++){
s3=s[i];
if (s3==s1){
newchar=s5;
}
else{
newchar=s[i];
System.Console.WriteLine("{0}",newchar);
}
}
}
catch (System.ArgumentOutOfRangeException e){
System.Console.WriteLine("{1}",e,err);
}
}
public static void Main(){
replacestr r=new replacestr();
r.getstr();
}
}












No comments yet... Be the first to leave a reply!