我需要拆分此文本
这真的很酷,我喜欢它。
进入这个
this
is
really
cool
,
and
i
like
it
.
知道怎么做吗?与空间分裂给出了这个
this
is
really
cool,
and
i
like
it.
我需要标点符号作为数组的单独元素
感谢
答案 0 :(得分:4)
你不能使用String.Split拆分“无”。
相反,您可以使用Regex.Split
执行此操作:
Regex r = new Regex(@"[ ]|(?=[,.])");
string[] items = r.Split(input);
在这种模式中,我们要么匹配一个空格(得到“消耗”),要么我们对标点符号进行预测(并且不要“消耗”它)。
答案 1 :(得分:2)
如果您关心的只是输出而且您并不是非常关心性能,那么为什么不这样做:
string[] splitSentence(string sentence) {
return sentence
.Replace(",", " , ")
.Replace(".", " . ")
.Split(' ', StringSplitOptions.RemoveEmptyEntries);
}
它会起作用! :)当然,如果你做关心表现,请参阅Scott的回答。
答案 2 :(得分:0)
我可能会用老式的方法来处理这个问题,然后简单地遍历每个角色。类似的东西:
static private IList<string> SplitString(string str)
{
List<string> lines = new List<string>();
StringBuilder line = new StringBuilder();
for(int i = 0; i < str.Length; ++i)
{
if (char.IsWhiteSpace(str[i]))
{
// split silently at whitespace
if (line.Length > 0)
lines.Add(line.ToString());
line.Clear();
}
else if (IsPunctuationCharacter(str[i]))
{
// split for punctuation and include each punctuation character as its own line
if (line.Length > 0)
lines.Add(line.ToString());
lines.Add(new string(new char[] { str[i] }));
line.Clear();
}
else
{
// all other characters get added to the current line
line.Append(str[i]);
}
}
if (line.Length > 0)
lines.Add(line.ToString());
return lines;
}
static private bool IsPunctuationCharacter(char c)
{
if (c == ',' || c == '.' || c == '?' || c == '!')
return true;
else
return false;
}