Ignore Alphanumeric words and Capitalize First letter of other words in string using C# and VB.Net

Last Reply 8 days ago By pandeyism

Posted 8 days ago

how to capitalize first letter of each word of a string but not the volume messurements 

Dim s As String = "Petrol 10lt  Iv Set  inj.panadol 10mg"
Dim s2 As String = StrConv(s, VbStrConv.ProperCase)
MessageBox.Show(s2.ToString)

the result is " Petrol 10Lt  Iv Set  Inj.Panadol 10Mg "

expected result is " Petrol 10lt  IV Set  Inj.Panadol 10mg "

You are viewing reply posted by: pandeyism 8 days ago.
Posted 8 days ago

Hey satabeach,

Please refer below sample.

Namespaces

C#

using System.Globalization;

VB.Net

Imports System.Globalization

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    string message = "";
    CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;
    TextInfo textInfo = cultureInfo.TextInfo;
    string s = "Petrol 10lt  Iv Set  inj.panadol 10mg";
    s = textInfo.ToTitleCase(s);
    string[] splitstring = s.Split(' ');
    bool first = true;
    foreach (var item in splitstring)
    {
        if (item.Any(char.IsLetter) && item.Any(char.IsDigit))
        {
            message += textInfo.ToLower(item) + " ";
        }
        else if (first)
        {
            message += textInfo.ToTitleCase(item + " ");
            first = false;
        }
        else
        {
            message += item + " ";
        }
    }
    Response.Write(message);
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim message As String = ""
    Dim cultureInfo As CultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture
    Dim textInfo As TextInfo = cultureInfo.TextInfo
    Dim s As String = "Petrol 10lt  Iv Set  inj.panadol 10mg"
    s = textInfo.ToTitleCase(s)
    Dim splitstring As String() = s.Split(" "c)
    Dim first As Boolean = True
    For Each item In splitstring
        If item.Any(AddressOf Char.IsLetter) AndAlso item.Any(AddressOf Char.IsDigit) Then
            message += textInfo.ToLower(item) & " "
        ElseIf first Then
            message += textInfo.ToTitleCase(item & " ")
            first = False
        Else
            message += item & " "
        End If
    Next
    Response.Write(message)
End Sub

Output

Petrol 10lt Iv Set Inj.Panadol 10mg