You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Framework中C#生成指定固定位模式随机数的方法

Generate Patterned Random Numbers in C# (.NET Framework)

Got it, let's break down how to generate a numeric string that follows your specified pattern—where fixed 0s stay put and xs get replaced with random digits. This is straightforward to implement in C# with .NET Framework, and I'll walk you through a clean, robust solution.

The Core Approach

The idea is simple: iterate over each character in your pattern string. For every x, replace it with a random digit (0-9); leave any fixed characters (like your 0s) untouched. We'll use a static Random instance to avoid duplicate sequences when generating numbers in quick succession.

Full Code Implementation

using System;

public class PatternedRandomGenerator
{
    // Static Random instance to ensure unique sequences across multiple calls
    private static readonly Random _randomGenerator = new Random();

    /// <summary>
    /// Generates a numeric string matching the input pattern
    /// </summary>
    /// <param name="pattern">Pattern where 'x' = random digit, other characters remain fixed</param>
    /// <returns>Generated patterned number string</returns>
    /// <exception cref="ArgumentException">Thrown if pattern is null/empty</exception>
    public static string GeneratePatternedNumber(string pattern)
    {
        if (string.IsNullOrWhiteSpace(pattern))
            throw new ArgumentException("Pattern cannot be null, empty, or whitespace.", nameof(pattern));

        char[] resultChars = pattern.ToCharArray();
        
        for (int i = 0; i < resultChars.Length; i++)
        {
            if (resultChars[i] == 'x')
            {
                // Convert random 0-9 integer to corresponding char (e.g., 5 → '5')
                resultChars[i] = (char)('0' + _randomGenerator.Next(0, 10));
            }
            // Fixed characters (like '0') are left as-is
        }

        return new string(resultChars);
    }

    // Example usage
    public static void Main()
    {
        string targetPattern = "xx0xxxx00xx0";
        string generatedNumber = GeneratePatternedNumber(targetPattern);
        Console.WriteLine($"Generated number: {generatedNumber}");
        // Sample output: 730921500460
    }
}

Key Details to Note

  • Static Random Instance: Creating a new Random each time you generate a number can lead to duplicate sequences if called rapidly (since it uses system clock as seed). Using a static instance avoids this issue.
  • Efficient Character Handling: We convert the pattern to a char[] instead of using string concatenation—this is more performant, especially for longer patterns.
  • Input Validation: The method checks for null/empty patterns to prevent unexpected behavior.
  • Flexibility: This solution works for any pattern, not just your specific one. If you later need a pattern like x1x2x3, it will still replace only the xs and keep the fixed digits.

Testing the Code

When you run the Main method, you'll get a unique numeric string matching your xx0xxxx00xx0 pattern every time. For example, you might see outputs like 450123400670, 980765400320, etc.

内容的提问来源于stack exchange,提问作者Bizzie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 19:42:32