如何用逗号分隔字符串 [英] How to seperate string with comma

查看:268
本文介绍了如何用逗号分隔字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何找到这种类型的输出



假设我的字符串是 -

string =usernameemail_idpassword;

并且在用逗号分隔后输出将会像



用户名,email_id,密码

请给我一些解决方案尽快

how to find output like this type

suppose my string is -
string = "usernameemail_idpassword";
and after seperate with comma the output will come like

"username,email_id,password"
pls send me some solutions as soon as possible

推荐答案

string[] words = string.Split(',');







foreach (string word in words)
	{
	    Console.WriteLine(word);
	}


1。现在分隔符字符(空格,逗号等)时,您可以将字符串拆分(分离)为子字符串,在这种情况下,您应该使用 string.Split()类似的方法在上面的解决方案1中指出。



2.但在你的情况下,你有一组连接的单词,它们之间没有分隔符。

在这种情况下你应该提供一些可以用于拆分的规则,就像在你的情况下,字符串中的所有单词具有相同的长度(8个字符)。因此,如果您有此规则,则解决方案是下一个:

1. You can split (separate) a string into sub-strings when you now the separators chars (spaces, coma, etc), and in that case you should use the string.Split() method like is indicated in "Solution 1" above.

2.But in your case you have a set of concatenated words with no separators between them.
In this case you should provide some rule that could be used for splitting, like in your case all words from the string has the same length (8 chars). So if you have this rule the the solution is the next one:
string input = "usernameemail_idpassword";
int length = 8;
int n = input.Length;
StringBuilder temp = new StringBuilder();
for(int i=0; i< n; i+=length)
{
    if (i > 0)
    {
        //Add the separator.
        temp.Append(",");
    }
    //Split the string using the "fixed length" rule.
    temp.Append(input.Substring(i, length));
}
// Get the result.
string result = temp.ToString();
Console.WriteLine(result);


这篇关于如何用逗号分隔字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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