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

如何动态将字符串内容替换为列表中匹配的指定值?

Solution: Dynamically Replace Lowercase Car Make with Proper Case from List

Here's how you can dynamically match the lowercase car make in your string with the properly capitalized version from your carMake list, then replace it before calling callFoo:

Step-by-Step Explanation & Code

  1. Retrieve the original string from CallGetLatestRecord()
  2. Extract the lowercase car make segment from the string (split on colons to get the middle part)
  3. Find the matching proper-case entry in your list using a case-insensitive comparison
  4. Replace the lowercase segment with the proper-case version and pass to callFoo

Here's the full implementation in your myFunction method:

using System.Linq; // Don't forget to include this for LINQ methods

public class YourClass
{
    // Your existing readonly list (class-level field)
    private readonly List<string> carMake = new List<string> { "Toyota", "Honda", "Audi", "Tesla" };

    public void myFunction()
    {
        string originalString = CallGetLatestRecord(); // Returns "a:toyota:c"
        
        // Split the string into segments using colon as delimiter
        string[] stringSegments = originalString.Split(':');
        
        // Validate the string format (ensure we have 3 segments)
        if (stringSegments.Length != 3)
        {
            // Handle invalid string format (adjust based on your needs)
            Console.WriteLine("Invalid string format from CallGetLatestRecord()");
            return;
        }
        
        string lowercaseMake = stringSegments[1];
        
        // Find the matching make from our list (case-insensitive match)
        string properCaseMake = carMake.FirstOrDefault(make => 
            make.Equals(lowercaseMake, StringComparison.OrdinalIgnoreCase));
        
        if (properCaseMake != null)
        {
            // Replace the lowercase part with the properly capitalized version
            string modifiedString = originalString.Replace(lowercaseMake, properCaseMake);
            callFoo(modifiedString); // Passes "a:Toyota:c" to callFoo
        }
        else
        {
            // Handle scenario where the make isn't in our list (adjust as needed)
            Console.WriteLine($"Car make '{lowercaseMake}' not found in list");
            callFoo(originalString);
        }
    }

    // Dummy methods to match your example structure
    private string CallGetLatestRecord() => "a:toyota:c";
    private void callFoo(string input) => Console.WriteLine(input);
}

Key Details:

  • Case-Insensitive Matching: Using StringComparison.OrdinalIgnoreCase ensures we match "toyota" to "Toyota" regardless of case, without culture-specific edge cases.
  • LINQ's FirstOrDefault: This efficiently finds the first matching entry in your list (returns null if no match exists, which we handle gracefully).
  • String.Replace: Since we've isolated the exact lowercase segment to replace, this method is straightforward and safe for your consistent string format.

Alternative Regex Approach

If you need more flexibility for varying string formats, you can use regex to target the middle segment directly:

using System.Text.RegularExpressions;

// ... inside myFunction ...
string modifiedString = Regex.Replace(originalString, @":(\w+):", match => 
{
    string lowercaseMake = match.Groups[1].Value;
    string properCaseMake = carMake.FirstOrDefault(m => m.Equals(lowercaseMake, StringComparison.OrdinalIgnoreCase));
    return properCaseMake != null ? $":{properCaseMake}:" : match.Value;
});

callFoo(modifiedString);

This regex targets the segment between two colons, replaces it with the proper-case version if found, otherwise leaves it unchanged.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:28:18