c# - 将字符串拆分为子字符串,节省大空间
问题描述
我有一个string
这样的填充物 -
".... . -.-- .--- ..- -.. ."
我需要将其拆分为substrings,但中间的空格也必须写入字符串数组。
public static string Decode(string morseCode)
{
string[] words = morseCode.Split(new char[] { ' ' });
...
}
我预计 :
words[0] = "....";
words[1] = ".";
words[2] = "-.--";
words[3] = " "; // <- Space in the middle should be preserved
words[4] = ".---";
...
解决方案
您可以尝试正则表达式以匹配所需的块:
using System.Linq;
using System.Text.RegularExpressions;
public static string Decode(string morseCode) {
string[] words = Regex.Matches(morseCode, @"(?<=^|\s).+?(?=$|\s)")
.Cast<Match>()
.Select(match => match.Value.All(c => char.IsWhiteSpace(c))
? match.Value
: match.Value.Trim())
.ToArray();
//Relevant code here
}
演示:
using System.Linq;
using System.Text.RegularExpressions;
...
string morseCode = ".... . -.-- .--- ..- -.. .";
string[] words = Regex.Matches(morseCode, @"(?<=^|\s).+?(?=$|\s)")
.Cast<Match>()
.Select(match => match.Value.All(c => char.IsWhiteSpace(c))
? match.Value
: match.Value.Trim())
.ToArray();
string report = string.Join(Environment.NewLine, words
.Select((word, i) => $"words[{i}] = \"{word}\""));
Console.Write(report);
结果:
words[0] = "...."
words[1] = "."
words[2] = "-.--"
words[3] = " "
words[4] = ".---"
words[5] = "..-"
words[6] = "-.."
words[7] = "."
推荐阅读
- .net-core - 未处理的异常。无法配置 HTTPS 端点。未指定服务器证书,找不到默认的开发者证书
- python - Django 找不到与查询匹配的电影
- python-3.x - 如何用 colorio 绘制 sRGB 色域切片?
- wordpress - Woocommerce:根据具体内容删除产品描述
- r - 如何从单个文本文件中提取不同的文章?
- node.js - 在 Node.js/mongoosedb 中更新个人资料信息后未更新帖子上的用户名
- java - Springboot 后端。如何从 FrontEnd(JSON 类型)接收包含 ARRAY 的对象
- php - 将数据库上传到主机后,无法在 WordPress 管理面板中编辑任何内容
- jquery - 如何在codeigniter中获取按钮单击的相应文本区域的值?
- c - 为什么使用和不使用“-fsanitize=undefined,address”的这段代码的结果不同?