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

C#转Java:如何实现String数组分隔符的Split方法转换

Converting C# String Split Logic to Java

Got it, let's work through converting those C# lines to Java properly. The key hangup here is that Java's String.split() method doesn't accept a String array directly like C# does—it relies on regex patterns for splitting instead.

Step-by-Step Conversion

First, let's recap your original C# code for context:

string[] stringSeparators = new string[] { "3B3D3B" };
string[] separatedHex = returnHex.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);

Since you're only using a single separator, we can simplify this in Java while matching the exact behavior of your C# code. Here's the equivalent:

// Define your separator (no need for an array when there's only one value)
String separator = "3B3D3B";

// Split using the separator—wrap with Pattern.quote() to avoid regex conflicts
String[] splitResult = returnHex.split(Pattern.quote(separator), -1);

// Filter out all empty entries to match C#'s StringSplitOptions.RemoveEmptyEntries
String[] separatedHex = Arrays.stream(splitResult)
                             .filter(str -> !str.isEmpty())
                             .toArray(String[]::new);

Key Details to Note:

  • Regex Safety: We use Pattern.quote(separator) to ensure any accidental regex special characters (like ., *, or +) in your separator don't break the split logic. Even though "3B3D3B" has no special characters, this is a safe habit to prevent bugs down the line.
  • Empty Entry Handling: Java's default split() ignores trailing empty strings but keeps empty strings in the middle. To mirror C#'s RemoveEmptyEntries (which removes all empty strings, no matter their position), we use a stream to filter out any empty elements.
  • For Multiple Separators: If your stringSeparators array ever had multiple values, you'd combine them into a regex "OR" pattern like this:
    String[] separators = {"3B3D3B", "OtherSeparator123"};
    String regexPattern = String.join("|", Arrays.stream(separators)
                                                 .map(Pattern::quote)
                                                 .toArray(String[]::new));
    String[] splitResult = returnHex.split(regexPattern, -1);
    String[] separatedHex = Arrays.stream(splitResult).filter(str -> !str.isEmpty()).toArray(String[]::new);
    

内容的提问来源于stack exchange,提问作者O.D

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:08:48