127k views
5 votes
What is the value of the variable named s2 after the following statements have been executed?

string s1 = "118-45-9271";
string s2 = "";
for (int i = 0; i < s1.Length; i++) {
if (s1[i] != '-') {
s2 += s1[i];
}
}
s2 = s2.Replace('-', '.');
a. 118-45-9271
b. 172954811
c. 118459271
d. 118.45.9271

User Maksee
by
7.6k points

1 Answer

3 votes

Final answer:

The value of variable 's2' is '118459271' after executing the code, as hyphens are removed from 's1' and no replacement occurs due to the absence of hyphens in the final string.

Step-by-step explanation:

The value of the variable named s2 after the given code has been executed is 118459271. The for loop iterates through each character in s1 and appends it to s2 only if the character is not a hyphen ('-'). After the loop, s2 contains all the numerical characters of s1 without hyphens.

The final statement s2.Replace('-', '.'); attempts to replace any remaining hyphens with periods, but since there are no hyphens left in s2, this line does not alter s2. Therefore, the correct answer is c. 118459271.

User Azamsharp
by
8.4k points