user3097712 user3097712 - 3 months ago 11
C# Question

Questions about Substring() in C#

I am not a C# programmer & need help. I have some questions:

when I have the string text='My car is nice', then what would be the output of the following lines:

(1) text.Substring(1,1);
(2) text.Substring(6,1);
(3) text.Substring(1,4).Replace('c','a');
(4) text.Substring(1,10).Replace('a','b').Replace(' ','t');


My conclusions are:

(1) 'y'
(2) ' is nice M' <== here, I started from 6 until 1 (or do I need to swap 1&6?)
(3) 'y c'
(4) 'ytcbrtist' <== here I replaced a with b & the space lines with t


I hope someone can help.

Best regards,

Answer

If you look at the doc of String.Substring Method (Int32, Int32) it says that:

public string Substring( int startIndex, int length )

Then:

(1) text.Substring(1,1);
(2) text.Substring(6,1);
(3) text.Substring(1,4).Replace('c','a');
(4) text.Substring(1,10).Replace('a','b').Replace(' ','t');

(1) 'y' // Indice 1 length 1
(2) ' ' // Indice 6 length 1  
(3) 'y aa' // Indice 1 length 4 and replacements 
(4) 'ytcbrtistn'// Indice 1 length 10 and replacements

See it live

Comments