user2537701
user2537701

Reputation:

VB6 string functions in C#

If Left(strText, 3) = "De " Then
    Mid(strText, 1, 1) = "d"
ElseIf Left(strText, 4) = "Van " Then
    Mid(strText, 1, 1) = "v"
End If

This above VB code needs to be translated into C#.

I know mid and left are

strText.Substring(1,1) and strText.Substring(0, 4)

but if I can't do

strText.Substring(1,1) = "v";

Do I need to do..

strText.Replace(strText.Substring(1,1), "v"))

instead?

There was no comment in the VB6 code. So I am only guessing what is going on here.

EDIT: Sorry Wrong version of code

Upvotes: 0

Views: 488

Answers (2)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239654

The first block of code tests whether the string starts with the characters Van, and if it does, it replaces the first character with a v.

So the easiest replacement would be:

if(strText.StartsWith("De ")) {
   strText = "d" + strText.Substring(1);
}else if(strText.StartsWith("Van ")) {
   strText = "v" + strText.Substring(1);
}

Upvotes: 2

shahkalpesh
shahkalpesh

Reputation: 33476

strText = "v" + strText.Substring(1)

Note that array index starts from 0. I am assuming that you are trying to put "v" at the 1st character position (which is 0) in the string.

EDIT: Note that string in .net is immutable (i.e. the contents of the string can't be modified in place) as compared to VB6 example where you can use Mid or Left to set a value at a specified character position.

The following will return a new string with modified contents, which should be assiged back to strText for you to overwrite the original contents.

strText.Replace(strText.Substring(1,1), "v"))

Moreover, this is not a good approach because of 2 things 1) If strText is "van", `strText.Substring(1,1) will return "a"

2) strText.Replace(strText.Substring(1,1), "v")) will replace all "a", not just the first.

Upvotes: 1

Related Questions