关于C#中的子串()的问题

时间:2016-08-21 15:15:07

标签: c#

我不是C#程序员&需要帮忙。我有一些问题:

当我有字符串text='My car is nice'时,那么以下行的输出是什么:

(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'
(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 

我希望有人可以提供帮助。

致以最诚挚的问候,

2 个答案:

答案 0 :(得分:2)

如果你查看String.Substring Method (Int32, Int32)的文档,就会说:

  

public string Substring(       int startIndex,       int length   )

然后:

(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

live

答案 1 :(得分:1)

1)'y'    OK
2)' ' The sixth character is 'r'. And the next one is space ' '.
3)'y aa' . You are taking 4 chars starting from first. It's 'y ca' . Later You replace c with a. 
4)'ytcbrtistn' . You take 10 chars starting from 2nd one. 'y car is n' . You replace a with b -> 'y cbr is n' . Later replace space with t.