C# code to check the first character in the string is an integer and then convert to hex if integer

Sree 0 Reputation points
2023-01-24T19:52:49.2266667+00:00

In the input script, check the first character of the input parameter. If it is a digit value, then convert the integer to hex.

For example input is 7fph7vfxbvkl then output becomes _x0037_fph7vfxbvkl .looking for a c# script for this

Thank you

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,346 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,204 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Michael Taylor 47,716 Reputation points
    2023-01-24T20:24:06.5166667+00:00

    This sounds like a homework assignment or perhaps exam question. Please post the code you have to implement this so far. Also please provide the context of what you're actually trying to do.

    For homework then please refer to Char.IsDigit. For conversion then take a look at the custom format specifiers defined here.


  2. Jack J Jun 24,281 Reputation points Microsoft Vendor
    2023-01-25T02:17:49+00:00

    @Sree, Welcome to Microsoft Q&A, you could try the following code to convert int to hex string successfully as you wanted.

    First, we could use val.ToCharArray()[0] to get the first char of string.

    Second, we could use Char.IsDigit(firstchar) to check if the char is number.

    Third, we could use v.ToString("X4") to get the hex string.

     static void Main(string[] args)
            {
               
                var str = ConvertHex("7fph7vfxbvkl");
            }
            public static string ConvertHex(string val)
            {
                string retval = "";
                char firstchar = val.ToCharArray()[0];
                if (Char.IsDigit(firstchar))
                {
                    int v = Convert.ToInt32(firstchar);
                    retval = string.Format("_x{0}_{1}", v.ToString("X4"),val.Remove(0,1));
    
                }
                return retval;
            }
    

    Result:

    User's image

    Hope my code could help you.

    Best Regards,

    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments