根据多个字符分隔符分割字符串
我有一个字符串“4,6,8\n9,4”,
我想根据它进行分割,并且 \n
输出数组应该是
4
6
8
9
4
编辑:
现在,当我输入时,我正在从控制台读取字符串控制台中如上所述的字符串,在后面的代码中我得到 "4,6,8\\n9,4"
。现在我想使用 "," 和 "\\n"
进行分割。我怎样才能改变表达方式?
I have a string "4,6,8\n9,4"
I want to split this based on ,and \n
Output array should be
4
6
8
9
4
Edit :
Now i am reading string from console , when i enter a string as above in console , in the code behind i get as "4,6,8\\n9,4"
. Now that i want to split using "," and "\\n"
. How can i change the expression ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
使用 string.Split(char [])
编辑
如果您收到任何不必要的空物品,请尝试以下操作 String.Split 方法(String[]、StringSplitOptions)
EDIT2
这适用于您更新的问题。将所有必要的分割字符添加到
char []
中。Use string.Split(char [])
EDIT
Try following if you get any unnecessary empty items. String.Split Method (String[], StringSplitOptions)
EDIT2
This works for your updated question. Add all the necessary split characters to the
char []
.另一种选择是使用 Regex.Split。当分割序列更复杂时,这非常有用。例如,如果空格也可以是分割定界符的一部分,例如:
那么:
请注意,使用的正则表达式“更容易接受” - 它忽略了 \n 之间的空“空格”,并且会接受“4 6 8 9 4” ” 同样 - 所以上面要表明一点:给猫剥皮的方法不止一种。
快乐编码。
Another option is to use Regex.Split. This is useful when the split sequences are more complex. For instance if spaces can also be part of the split delimiters such as:
Then:
Note that the regular expression used is "more accepting" - it ignored the empty "space" between the \n's and it would accept "4 6 8 9 4" just the same - so the above to to show a point: there is more than one way to skin a cat.
Happy coding.
但这一定是一个骗局...
编辑:解决评论。
此代码:
输出:
编辑:从控制台读取输入是不同的。手动输入时
\n
不同。But this has to be a dupe...
EDIT: Addressing the comment.
This code:
Outputs this:
EDIT: Reading input from the console is different.
\n
is different when entered manually.以防万一您没有正确打印/查看它:
Just in case you are not printing / seeing it properly:
您可以执行 string.Replace('\n',',') 后跟 string.split(',') 吗?
Can you do a string.Replace('\n',',') followed by the string.split(',') ?
输出是一个字符串数组:
output is an array of strings:
对于每种情况
for every cases