简体   繁体   中英

Substring in C#

I have string "10-1283-01" the length going to be same , i want to check is that string like "10-xxxx-0x" only want first 3 character like "10-" and last but one two character like "-0".

So I am diving/Substring something like below. for first3 its giving me required string but for lastPart its giving me ArgumentOutOfRangeException.

Please let me know how i will get -0 string? Thanks in Advance

  string partnoveri = lpartno.Text;
    string first3=partnoveri.Substring(0, 3);
    string lastPart = partnoveri.Substring(partnoveri.IndexOf("-0"),partnoveri.Length-1);

The C# Substring method is not

String.Substring( int startIndex, int endIndex )

as your code suggests, rather it is

String.Substring( int startIndex [, int numberofCharacters ] )

Given that, if you're looking for two characters, you'd use:

string lastPart = partnoveri.Substring(partnoveri.IndexOf("-0"), 2);

That being said, I'd opt for @KMC's regular expression solution. While Substring will work in the case of your example, it will fail if the fourth character is zero, as in 10-0283-01

why dont you use regular expression?

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;

using System.Text.RegularExpressions;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            var pattern = "[0-9]{2}-[0-9]{4}-[0-9]{2}";
            var input = "10-1283-01";

            var matches = Regex.Matches(input, pattern);
            if(Regex.IsMatch(input, pattern))
            {
                Console.WriteLine("MATCH");
            }



        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }




}

To receive two last characters you can use substring like below:

partnoveri.Substring(partnoveri.Length-2, 2);

You can also use Regular Expression for this case.

Just reading about Ranges introduces in C# 8.0 spec.

Reading this question:

I have string "10-1283-01" the length going to be same , i want to check is that string like "10-xxxx-0x" only want first 3 character like "10-" and last but one two character like "-0"."

one can do (since c# 8.0 specs):

string partno = "10-1283-01";
Console.WriteLine($"{partno[0..3]}");    // returns "10-"
Console.WriteLine($"{partno[^3..^1]}");  // returns "-0"

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