C# Programming - Strings - Discussion

Discussion Forum : Strings - General Questions (Q.No. 5)
5.
Which of the following will be the correct output for the C#.NET code snippet given below?
String s1 = "Nagpur";
String s2;
s2 = s1.Insert(6, "Mumbai"); 
Console.WriteLine(s2);
NagpuMumbair
Nagpur Mumbai
Mumbai
Nagpur
NagpurMumbai
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
8 comments Page 1 of 1.

Dev said:   7 years ago
String is 1 index based thats why its start from 1.

David said:   10 years ago
Shouldn't this return an argument out of range exception?

Constrantine said:   1 decade ago
Then why in question 2, in substring function 12 is not considered as index ?

String s1 = "ALL MEN ARE CREATED EQUAL";
String s2;
s2 = s1.Substring(12, 3);
Console.WriteLine(s2);

Vinod bhosale said:   1 decade ago
If we see a String as an array of the characters then its indexing will start from 0 as it is known & it can also be considered as dynamic array.

In the rule of array 0 is the first index.

So if NAGPUR is stored in a string it will store following value at this index:

0 - N
1 - A
2 - G
3 - P
4 - U
5 - R

So if we look at line below :

s2 = s1. Insert (6, "Mumbai") ;.

It says to put the mumbai at index 6 which is a free unused space & hence instead of replacing the 'R' it stores the 'MUMBAI' after 'NAGPUR' is completed.
(1)

Newbie said:   1 decade ago
According to msdn site of String.Insert() method, it says index here is zero-based, but how come can the index of a string be equal to its length?

Rajitha Reddy said:   1 decade ago
The Insert() function in String Class will insert a String in a specified index in the String instance.

string string.Insert(int ind,string str)

Parameters:

ind - The index of the specified string to be inserted.

str - The string to be inserted.

Returns:

String - The result string.

Exceptions:

System.ArgumentOutOfRangeException: startIndex is negative or greater than the length of this instance

System.ArgumentNullException : If the argument is null.

Ashish Tiwari said:   1 decade ago
How will be the indexing of string here? from 0 or from 1?

Asish Kumar Satpathy said:   1 decade ago
If the expression will be like this "s2=s1.insert (5, "mumbai") ;".
Then what will be the output?

Post your comments here:

Your comments will be displayed after verification.