简体   繁体   中英

String Get/Update Numeric Value After Specific Character

I have a console app with alphanumeric input. I want to extract/update the numeric value from specific position of a character. All characters are unique. No the same characters in an input. For example in my program I want to extract/update numeric value from specific char R. R is unique. It's always 1 and followed by numbers. Please help. Here's my program.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp16
{
    class Program
    {
        static void Main(string[] args)
        {
            var input = "JPR5AU75";
            Console.WriteLine(GetNumericValue(input,'R'));
            //Expected output=5
            Console.WriteLine(UpdateNumericValue(input, 'R', 7));
            //Expected output=JPR7AU75

            input = "PR2.9AU75";
            Console.WriteLine(GetNumericValue(input, 'R'));
            //Expected output=2.9
            Console.WriteLine(UpdateNumericValue(input, 'R', 3.5));
            //Expected output=PR3.5AU75

            input = "PKLR555AU75";
            Console.WriteLine(GetNumericValue(input, 'R'));
            //Expected output=555
            Console.WriteLine(UpdateNumericValue(input, 'R', 765));
            //Expected output=PKLR765AU75
            Console.ReadLine();
        }
        static string GetNumericValue(string input, char c)
        {
            var value = "Get numeric value from position of charcter c";
            return value;
        }
        static string UpdateNumericValue(string input, char c, double newVal)
        {
            var value = "Replace numeric value from input where character position starts with c";
            return value;
        }
    }
}

Here is the sample code for your methods. Running Code here

Time Complexity will be O(N) in worst case, N -> length of the input

    static string GetNumericValue(string input, char c)
    {
        int charIndex = input.IndexOf(c);

        StringBuilder sb = new StringBuilder();
        int decimalCount = 0;

        for (int i = charIndex + 1; i < input.Length; i++)
        {
            if (char.IsNumber(input[i]) || input[i] == '.')
            {
                if (input[i] == '.') decimalCount++;
                if (decimalCount > 1) break;

                sb.Append(input[i]);
            }
            else break;
        }
        return sb.ToString();
    }

    static string UpdateNumericValue(string input, char c, double newVal)
    {  
        var numericValue = GetNumericValue(input, c);
        return input.Replace(c + numericValue, c + newVal.ToString());            
    }

You can use Regular Expressions to extract the desired part:

$@"{c}([-+]?[0-9]+\.?[0-9]*)" Will match the character c and capture in a groupe 0 or 1 sign, followed by 1 or more digits, followed by 0 or 1 dot, followed by 0 or more digits

using System.Text.RegularExpressions;

// returns an empty string if no match
static string GetNumericValue(string input, char c)
{
    Regex regex = new Regex($@"{Regex.Escape(c.ToString())}([-+]?\d+\.?\d*)");
    var match = regex.Match(input);
    if (match.Success)
    {
        return match.Groups[1].Value;
    }
    return string.Empty;
}

The replacement can use the value get above and will replace the first matched string with the expected number:

// returns the unchanged input if no match
static string UpdateNumericValue(string input, char c, double newVal)
{
    var needle = $"{c}{GetNumericValue(input, c)}"; // get the numeric value prepended with the searched character

    if (!string.IsNullOrEmpty(needle))
    {
        var regex = new Regex(Regex.Escape(needle));
        return regex.Replace(input, $"{c}{newVal.ToString()}", 1); // replace first occurence
    }
    return input;
}

var input = "JPR5AU75";

Console.WriteLine(GetNumericValue(input,'R'));
//Expected output=5
Console.WriteLine(UpdateNumericValue(input, 'R', 7));
//Expected output=JPR7AU75

input = "PR2.9AU75";
Console.WriteLine(GetNumericValue(input, 'R'));
//Expected output=2.9
Console.WriteLine(UpdateNumericValue(input, 'R', 3.5));
//Expected output=PR3.5AU75

input = "PKLR555AU75";
Console.WriteLine(GetNumericValue(input, 'R'));
//Expected output=555
Console.WriteLine(UpdateNumericValue(input, 'R', 765));
//Expected output=PKLR765AU75
//Console.ReadLine();

input = "ABCDEF";
Console.WriteLine(GetNumericValue(input, 'C'));
//Expected output=""
Console.WriteLine(UpdateNumericValue(input, 'C', 42));
//Expected output="ABCDEF"

input = "ABCDEF";
Console.WriteLine(GetNumericValue(input, 'F'));
//Expected output=""
Console.WriteLine(UpdateNumericValue(input, 'F', 42));
//Expected output="ABCDEF"

input = "666ABC666ABC555";
Console.WriteLine(GetNumericValue(input, 'C'));
//Expected output="666"
Console.WriteLine(UpdateNumericValue(input, 'C', 42));
//Expected output="666ABC42ABC555"

Try it yourself

I have an easier to understand solution:

    static string GetNumericValue(string input, char c)
    {
        int indexStartOfValue = input.IndexOf(c) + 1;       
        
        int valueLength = 0;
        while(Char.IsDigit(input[indexStartOfValue + valueLength]) || input[indexStartOfValue + valueLength] == '.')
            valueLength ++;
        
        return input.Substring(indexStartOfValue, valueLength);
    }
    
    static string UpdateNumericValue(string input, char c, double newVal)
    {
        var numericValue = GetNumericValue(input, c);
        return input.Replace(c + numericValue, c + newVal.ToString());
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM