Rakesh
Rakesh

Reputation: 2790

Translating VB.NET string manipulation to C#

I am trying to convert VB.NET code to C# code.

This is my VB.NET code:

Dim Part1 As String = "Some string"
Dim p_str As String
For I = 1 To Len(Part1)
    p_str = Chr(Asc(Mid$(Part1, I, 1)) + 17)
Next

I have translated it to C# like this:

string Part1 = "Some string";
string p_str = null;
for (I = 0; I <= Part1.Length - 1; I++)
{
    p_str = Convert.ToChar((Part1.IndexOf(Part1.Substring(I, 1)) + 65) + 17).ToString();
}

Can anyone tell me whether it’s correct?

Upvotes: 2

Views: 829

Answers (3)

Dave Doknjas
Dave Doknjas

Reputation: 6542

You don't need a reference to Microsoft.VisualBasic (edit: see the comments - in this case you do need it), and your 'for' loop condition should be "I <= Part1.Length":

string Part1 = "Some string";
string p_str = null;
for (int I = 1; I <= Part1.Length; I++)
{
    'edit: I thought this would work, but it doesn't:
    p_str = ((char)(Convert.ToInt32(Part1[I - 1]) + 17)).ToString();
    'edit: the following works, with "Strings.Chr" and "Strings.Asc" remaining:
    p_str = Microsoft.VisualBasic.Strings.Chr(Microsoft.VisualBasic.Strings.Asc(Part1[I - 1]) + 17).ToString(); 
}

Upvotes: 1

user2480047
user2480047

Reputation:

You have to add a refererence to Microsoft.Visualbasic (Top menu, under "Add Reference" and the ".NET" Tab) and use Strings.Chr and Strings.Asc if you want to emulate perfectly the behaviour of Chr and Asc (as warned in this link by Garry Shutler's answer). Your code would become:

string Part1 = "Some string";
string p_str = null;
for (int I = 0; I < Part1.Length; I++)
{
    p_str = Strings.Chr(Strings.Asc(Part1.Substring(I, 1)) + 17).ToString();
}

CLARIFICATION 1: the original code you are posting is not (pure) VB.NET, it is VB (VB.NET allows most of the VB commands to be written in). That's why so many changes are required (for example: changing the starting index); VB.NET is much more similar to C#.NET than this (as shown below).

CLARIFICATION 2: it is generally accepted that the C# translations for VB's Asc and Chr are mere casts (to int and char respectively), as you can see in the most voted answer in the aforementioned link. THIS IS WRONG. Test this code with both alternatives to confirm that only the Strings options deliver always the right result.

"PROPER" VB.NET CODE:

Dim Part1 As String = "Some string"
Dim p_str As String = Nothing
For I As Integer = 0 To Part1.Length - 1
    p_str = Chr(Asc(Part1.Substring(I, 1)) + 17)
Next

Upvotes: 6

Ahmed ilyas
Ahmed ilyas

Reputation: 5822

pretty much but you need to declare the I variable in your for loop. Correction:

for (int I = 0; I <= Part1.Length-1; I++)
 {
...

 }

Upvotes: 0

Related Questions