我怎么能在数组中将chars ins拆分为c#中的字符串? [英] how can i inculde chars in array thats splits a string in c#?

查看:79
本文介绍了我怎么能在数组中将chars ins拆分为c#中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我分割字符串时,它会忽略用于分割字符串的字符,但我也需要它们.
例如

when i split a string it ignores the chars which are used to split the string but i need them too.
for eg

char[] delimiterChar = { ' ', '.','=','(',')'};
string input = "int i =0. printf(asma).";
string[] tokens = input.Split(delimiterChar);
foreach (string i in tokens)
{
    Console.WriteLine(i);
}



其输出



its output

int 
i

0

printf
asma




但我想要这样的输出.




but i want the output like this.

int
i
=
0
.
printf
(
asma
)
.



我怎么才能得到它.我尽力解释了我的问题



how can i get it. i tried my best to explain my question

推荐答案

拆分不会为您提供帮助.

这不是一件容易的事,您也许可以使用正则表达式(也可以不是那么复杂的正则表达式)来完成,并使用Regex.Split方法在输出中包含字符(有一个示例此处 [ Google [
Split is not going to help you.

This is not a simple thing to do, you may be able to do it with a regex (and not that complex a regex either) and use the Regex.Split method to include the characters in the output, (there is an example here[^] that works, but with a different set of characters).

However, what you are actually trying to do is more complex that that probably provides. You need a Parser - have a google and see if anything suits. Google[^] may help.

I think that you may find that going for a full on parser will reduce your frustration later!


您必须一次将字符串分割成一个字符.像这样的东西:

You have to split the string up a character at a time. Something like this:

string alphanum = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string test = "int i=0. printf(asma).";
List<string> parts = new List<string>();
string temp = test;
string word = "";
while (temp.Length > 0)
{
    string c = temp.Substring(0,1);
    temp = temp.Substring(1);
    if (!alphanum.Contains(c))
    {
        if (!string.IsNullOrEmpty(word))
        {
            parts.Add(word);
            word = "";
        }
        parts.Add(c);
    }
    else
    {
        word += c;
    }
}



上面的代码未经测试,因此您可能需要对其进行一些调整.最终结果应该是所有组成部分都在parts集合中.



The code above is not tested, so you may need to tweak it a bit. The end result should be all of the component parts being in the the parts collection.


这篇关于我怎么能在数组中将chars ins拆分为c#中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆