考虑我有一个包含这么多管道分隔数据的字符串。
String s="hskdhkdh|eeeee|eeeee|eeeee|eeeesds|ddd\nsdsfdfdf|dsfdfdf|dfdsf\ndsfdsf|sdfsfdsfds|cvcxvv|hkdh\nhdskdh|hdkshdkd|n\nkho|jljoas|sbkhash|bkshoshak\nhksashalsha|bkgaskgask|hkhlv|skhgdskdg|bgdsjdgsj|gklgau"
我这个字符串,有太多的新行字符(\ n)但是我想要\ n只在每第6次出现一次管道(|)
之前所以结果应该是
String s="hskdhkdh|eeeee|eeeee|eeeee|eeeesds|ddd\nsdsfdfdf|dsfdfdf|dfdsfdsfdsf|sdfsfdsfds|cvcxvv|hkdh\nhdskdh|hdkshdkd|nkho|jljoas|sbkhash|bkshoshak\nhksashalsha|bkgaskgask|hkhlv|skhgdskdg|bgdsjdgsj|gklgau"
我正在使用控制台应用程序中的C#.. 有人可以帮助我吗
答案 0 :(得分:2)
您可以尝试使用 Linq :
String s =
"hskdhkdh|eeeee|eeeee|eeeee|eeeesds|ddd\nsdsfdfdf|dsfdfdf|dfdsf\ndsfdsf|sdfsfdsfds|cvcxvv|hkdh\nhdskdh|hdkshdkd|n\nkho|jljoas|sbkhash|bkshoshak\nhksashalsha|bkgaskgask|hkhlv|skhgdskdg|bgdsjdgsj|gklgau";
// Split by |
// Remove extra \n
// Join back by |
String result = String.Join("|", s
.Split('|')
.Select((item, index) => ((index > 0) && (index % 5 == 0))
? item
: item.Replace("\n", "")));
// Test:
// hskdhkdh|eeeee|eeeee|eeeee|eeeesds|ddd
// sdsfdfdf|dsfdfdf|dfdsfdsfdsf|sdfsfdsfds|cvcxvv|hkdh
// hdskdh|hdkshdkd|nkho|jljoas|sbkhash|bkshoshak
// hksashalsha|bkgaskgask|hkhlv|skhgdskdg|bgdsjdgsj|gklgau
Console.Write(result);
答案 1 :(得分:0)
var bits = s.Split('|'); // Divide into bits
for(int i = 0; i < bits.Length; i++){
if(i % 6 == 0){
bits[i] += "\n";
}
}
var done = string.Join(bits, '|');
这应该有用(如果它编译,我直接在回复中编码)
答案 2 :(得分:0)
您最好的选择可能是使用string.split()
方法将其更改为array
substrings
,然后使用Stringbuilder
和counter
变量来分割字符串。
我将使用您的字符串编写下面的代码。
string s = "hskdhkdh | eeeee | eeeee | eeeee | eeeesds | ddd | sdsfdfdf | dsfdfd | dfdsfdsfdsf | sdfsfdsfds | cvcxvv | hkdh | hdskdh | hdkshdkd | nkho | jljoas | sbkhash | bkshoshak | hksashalsha | bkgaskgask | hkhlv | skhgdskdg | bgdsjdgsj";
string[] substrings = s.Split('|');
int counter = 1;
StringBuilder sb = new StringBuilder();
foreach (string sub in substrings)
{
sb.Append(sub + "|");
if (counter % 6 == 0)
{
sb.Append("\n");
}
counter++;
}
s = sb.ToString();