P. 1
Rob Miles CSharp Yellow Book 2010

Rob Miles CSharp Yellow Book 2010

|Views: 7|Likes:
Published by Kiran Kumar

More info:

Published by: Kiran Kumar on Nov 23, 2010
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

04/08/2015

pdf

text

original

It is probably worth spending a few moments considering the string type in a bit more
detail. This is because it gives you a lot of nice extra features which will save you a lot
of work. These are exposed as methods which you can call on a string reference. The
methods will return a new string, transformed in the way that you ask. You can sort out
the case of the text, trim spaces off the start and end and extract sub-strings using these
methods.

4.11.1

String Manipulation

Strings are rather special. I regard them as a bit like bats. A bat can be regarded as
either an animal or a bird in many respects. A string can be regarded as either an object
(referred to by means of a reference) or a value (referred to as a value).

This hybrid behaviour is provided because it makes things easier for us programmers.
However it does mean that we have to regard strings as a bit special when you are
learning to program, because they seem to break some of the rules that we have learnt.

It is very important that you understand what happens when you transform a string.
This is because, although strings are objects, they don't actually behave like objects all
the time.

string s1="Rob";
string s2=s1;
s2 = "different";
Console.WriteLine(s1 + " " + s2);

If you think you know about objects and references, you should be expecting s1 to
change when s2 is changed. The second statement made the reference s2 refer to the
same object as s1, so changing s2 should change the object that s1 refers to as well.
To find out more about this, take a look at section 4.4.1.

This does not happen though, because C# regards an instance of a string type in a
special way. It calls it immutable. This is because programmers want strings to behave
a bit like values in this respect.

4.11.2

Immutable strings

The idea is that if you try to change a string, the C# system instead creates a new string
and makes the reference you are "changing" refer to the changed one. In other words,
when the system sees the line:

s2 = "different";

- it makes a new string which contains the text "different" and makes s2 refer to that.
The thing that s1 is referring to is unchanged. So, after the assignment s1 and s2 no
longer refer to the same object. This behaviour, never allowing a thing to be changed
by making a new one each time it is required, is how the system implements
immutable.

You might ask the question: "Why go to all the trouble?" It might seem all this hassle
could be saved by just making strings into value types. Well, no. Consider the situation
where you are storing a large document in the memory of the computer. By using

references we only actually need one string instance with the word ―the‖ in it. All the

occurrences in the text can just refer to that one instance. This saves memory and it
also makes searching for words much faster.

Creating Solutions

The power of strings and chars

C# Programming © Rob Miles 2010

125

4.11.3

String Comparison

The special nature of strings also means that you can compare strings using equals and
get the behaviour you want:

if ( s1 == s2 )
{

Console.WriteLine("The same");

}

If s1 and s2 were proper reference types this comparison would only work if they
referred to the same object. But in C# the comparison works if they contain the same
text. You can use an equals method if you prefer:

if ( s1.Equals(s2) )
{

Console.WriteLine("Still the same");

}

4.11.4

String Editing

You can read individual characters from a string by indexing them as you would an
array:

char firstCh = name[0];

This would set the character variable firstCh to the first character in the string.
However, you can't change the characters:

name[0] = 'R';

- would cause a compilation error because strings are immutable.

You can pull a sequence of characters out of a string using the SubString method:

string s1="Rob";
s1=s1.Substring(1,2);

The first parameter is the starting position and the second is the number of characters to
be copied. This would leave the string "ob" in s1.(remember that strings are indexed
starting at location 0).

You can leave out the second parameter if you like, in which case all the characters up
to the end of the string are copied:

string s1="Miles";
s1=s1.Substring(2);

- would leave "les" in s1.

4.11.5

String Length

All of the above operations will fail if you try to do something which takes you beyond
the length of the string. In this respect strings are just like arrays. It is also possible to
use the same methods on them to find out how long they are:

Console.WriteLine ( "Length: " + s1.Length);

The Length property gives the number of characters in the string.

4.11.6

Character case

Objects of type string can be asked to create new, modified, versions of themselves in
slightly different forms. You do this by calling methods on the reference to get the
result that you want:

s1=s1.ToUpper();

Creating Solutions

Properties

C# Programming © Rob Miles 2010

126

The ToUpper method returns a version of the string with all the letters converted to
UPPER CASE. No other characters in the string are changed. There is a corresponding
ToLower method as well.

4.11.7

Trimming and empty strings

Another useful method is Trim. This removes any leading or trailing spaces from the
string.

s1=s1.Trim();

This is useful if your users might have typed " Rob " rather than "Rob". If you don't
trim the text you will find equals tests for the name will fail. There are TrimStart and
TrimEnd methods to just take off leading or trailing spaces if that is what you want. If
you trim a string which contains only spaces you will end up with a string which
contains no characters (i.e. its length is zero).

4.11.8

Character Commands

The char class also exposes some very useful methods which can be used to check the
values of individual characters. These are static methods which are called on the
character class and can be used to test characters in a variety of ways:

char.IsDigit(ch)

returns true if the character is a digit (0
to 9)

char.IsLetter(ch)

returns true if the character is a letter (a
to z or A to Z)

char.IsLetterOrDigit(ch)

returns true if the character is a letter or
a digit

char.IsLower(ch)

returns true if the character is a lower
case letter

char.IsUpper(ch)

returns true if the character is an upper
case letter

char.IsPunctuation(ch)

returns true if the character is a
punctuation character

char.IsWhiteSpace(ch)

returns true if the character is a space,
tab or newline

You can use these when you are looking through a string for a particular character.

4.11.9

String Twiddling with StringBuilder

If you really want to twiddle with the contents of your strings you will find the fact that
you can't assign to individual characters in the string a real pain. The reason you are
suffering is that strings are really design to hold strings, not provide a way that they can
be edited. For proper string editing C# provides a class called StringBuilder. It is
found in the System.Text namespace.

It works a lot like a string, but you can assign to characters and even replace one string
with another. It is also very easy to convert between StringBuilder instances and
strings. You should look this up if you have a need to do some proper editing.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->