| Printable Version
String Extraction And Insertion In C#
By J.V.Ravichandran
|
The following is the class that replaces one string with another string specified by the user. Just as in Java or any other language, C#(C-Sharp) also has string manipulators but since we are talking about original pieces of codes, I have written the following piece of original method called getstr--which gets a string from another
through an object of the 'string' class ! Java's string class has an unique behaviour, in that it takes strings into constructors and then manipulates and gives the result. Only an experienced OOPS programmer can tackle string manipulation in Java. But in C#, string
manipulation is as easy as it has always been in C++. Just use objects of string class 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 and displays your own error message. Of course, another way of string manipulation is through the class indexers - the unique feature of C# which allows access to the class members as if they were arrays
and not objects !
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();
}
}
|