Help convert VB.NET code to C#

T

Thonglao Rud

Hi all!
I'm new to programming in .NET and I want to convert a function from VB.NET to C#.
[VB.NET - from FxLib]
Public Function ProperCase(ByVal cString As String) As String

'Create the StringBuilder
Dim sb As StringBuilder = New StringBuilder(cString.ToLower())

Dim i As Integer, j As Integer = 0
Dim nLength As Integer = cString.Length

For i = 0 To nLength - 1 Step i + 1
'look for a blank space and once found make the next character to uppercase
If (i = 0) Or (Char.IsWhiteSpace(cString.Chars(i))) Then
'Handle the first character differently
If i = 0 Then
j = i
Else
j = i + 1
End If

'Make the next character uppercase and update the stringBuilder
sb.Remove(j, 1)
sb.Insert(j, Char.ToUpper(cString.Chars(j)))
End If
Next
Return sb.ToString()
End Function

[C# - port by me]
public string ProperCase(string cString)
{
StringBuilder sb = new StringBuilder(cString.ToLower());
int i, j = 0;
int nLength = cString.Length;
for(i = 0; i < nLength; i++)
{
if (i == 0 || Char.IsWhiteSpace(cString))
{
if (i == 0)
j = i;
else
j = i + 1;
sb.Remove(j, 1);
sb.Insert(j, Char.ToUpper(cString));
}
}
return sb.ToString();
}

But when I call it from my application, its result is not correct:
"abc def ghi" --> "Abc ef hi"

Any ideas?
Thank
 
U

Uri Dor

It seems your problem is in debugging the C# code.
First of all, the Insert line in VB accesses index j and in C# accesses
index i...
Besides, I don't see how you can replace to uppercase when you remove
the char before getting its uppercase.
Did you try single-stepping this code at all??

Anyway, I'd recommend iterating the input string and copying it char by
char into a StringBuilder, switching case as necessary. Iterating a
collection (in this case, a string which is a collection of chars) while
changing it is a bad idea.

Happy debugging...
 
N

Nico Vrouwe

Hi,

Change
sb.Insert(j, Char.ToUpper(cString));
to
sb.Insert(j, Char.ToUpper(cString[j]));
(cString[J] instead of I)

HTH,
/Nico
 
T

Thonglao Rud

Nico said:
Hi,

Change
sb.Insert(j, Char.ToUpper(cString));
to
sb.Insert(j, Char.ToUpper(cString[j]));
(cString[J] instead of I)

HTH,
/Nico

It works like a charm! Thank you both.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top