Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在字符串中的冒号之间添加空格_C#_.net - Fatal编程技术网

C# 在字符串中的冒号之间添加空格

C# 在字符串中的冒号之间添加空格,c#,.net,C#,.net,预期用户输入: Apple : 100 Apple:100 Apple: 100 Apple :100 Apple : 100 Apple :100 Apple: 100 Apple : 100 string input = "Apple:100"; if (input.Contains(":")) { string firstPart = input.Split(':').First(); string lastPart = input.S

预期用户输入:

Apple : 100

Apple:100

Apple: 100

Apple :100

Apple   :   100

Apple  :100

Apple:  100
Apple : 100
 string input = "Apple:100";

 if (input.Contains(":"))
 {
    string firstPart = input.Split(':').First();

    string lastPart = input.Split(':').Last();

    input = firstPart.Trim() + " : " + lastPart.Trim();
 }
预期结果:

Apple : 100

Apple:100

Apple: 100

Apple :100

Apple   :   100

Apple  :100

Apple:  100
Apple : 100
 string input = "Apple:100";

 if (input.Contains(":"))
 {
    string firstPart = input.Split(':').First();

    string lastPart = input.Split(':').Last();

    input = firstPart.Trim() + " : " + lastPart.Trim();
 }
冒号之间只需要1个空格

string input = "Apple   :     100";
input = new string(input.ToCharArray()
                 .Where(c => !Char.IsWhiteSpace(c))
                 .ToArray());
input = input.Replace(":", " : ");
代码:

Apple : 100

Apple:100

Apple: 100

Apple :100

Apple   :   100

Apple  :100

Apple:  100
Apple : 100
 string input = "Apple:100";

 if (input.Contains(":"))
 {
    string firstPart = input.Split(':').First();

    string lastPart = input.Split(':').Last();

    input = firstPart.Trim() + " : " + lastPart.Trim();
 }
上面的代码使用的是
Linq
,但是有没有考虑到性能的更短或更高效的代码


任何帮助都将不胜感激。

您可以使用以下一行:

input = string.Join(" : ", input.Split(':').Select(x => x.Trim()));
这比两次拆分更有效。但是,如果您想要更高效的解决方案,可以使用
StringBuilder

var builder = new StringBuilder(input.Length);
char? previousChar = null;
foreach (var ch in input)
{
    // don't add multiple whitespace
    if (ch == ' ' && previousChar == ch)
    {
        continue;
    }

     // add space before colon
     if (ch == ':' && previousChar != ' ')
     {
         builder.Append(' ');
     }

     // add space after colon
     if (previousChar == ':' && ch != ' ')
     {
          builder.Append(' ');
     }


    builder.Append(ch);
    previousChar = ch;
}

编辑:正如@Jimi在评论中提到的,foreach版本似乎比LINQ慢。

您可以尝试这种老式的字符串操作:

int colonPos = input.IndexOf(':');
if (colonPos>-1)
{
    string s1 = input.Substring(0,colonPos).Trim();
    string s2 = input.Substring(colonPos+1, input.Length-colonPos-1).Trim();
    string result = $"{s1} : {s2}";
}
我不知道它是否更有效

编辑: 这一个更快更简单(在0.132秒内完成100000次训练集迭代):

您可以使用正则表达式:

string input = "Apple:            100";

// Matches zero or more whitespace characters (\s*) followed by 
// a colon and zero or more whitespace characters
string result = Regex.Replace(input, @"\s*:\s*", " : "); // Result: "Apple : 100"

我不确定一个字符串生成器和缩短到一个数组会有多大的性能,但是你可以试试这样的方法

string input = "Apple:100";

if (input.Contains(":"))
{
  string[] parts = input.Split(':');

  StringBuilder builder = new StringBuilder();
  builder.Append(parts[0].Trim());
  builder.Append(" : ");
  builder.Append(parts[1].Trim());
  input = builder.ToString();
}

您指出第一个单词没有空格。因此,在我看来,最有效的非正则表达式解决方案是从字符串中删除所有空格(因为您不需要任何空格),然后用
替换

string input = "Apple   :     100";
input = new string(input.ToCharArray()
                 .Where(c => !Char.IsWhiteSpace(c))
                 .ToArray());
input = input.Replace(":", " : ");

Fiddle

既然你问了,下面是相似方法之间的比较:

介绍的两种方法和其他两种在某些细节上不同的方法。

string.Join(“[分隔符]”,string.Split())

此方法使用分隔符将
.Split(char[])
生成的字符串数组粘在一起,该数组为原始字符串的每个子字符串创建一个字符串。子字符串是使用char数组参数中指定的字符作为分隔符标识符生成的。
StringSplitOptions.RemoveEmptyEntries
参数指示仅返回非空子字符串。

string output = string.Join(" : ", input.Split(new[] { ":", " " }, StringSplitOptions.RemoveEmptyEntries));

StringBuilder.Append(子字符串(IndexOf([Separator]))

(未优化:
TrimStart()
TrimEnd()
在这里使用)

以下是5种不同条件下的测试结果:
(我提醒自己要始终测试
.exe
,而不是
IDE

调试模式32位-Visual Studio IDE
调试模式64位-Visual Studio IDE
发布模式64位-Visual Studio IDE
调试模式64位-可执行文件
发布模式64位-可执行文件

样本测试:

string input = "Apple   :   100";

Stopwatch sw = new Stopwatch();
sw.Start();

// Counter test StringBuilder    
StringBuilder sb1 = new StringBuilder();
const string Separator = " : ";
for (int i = 0; i < 1000000; i++)
{
    int SplitPosition = input.IndexOf(':');
    sb1.Append(input.Substring(0, SplitPosition).TrimEnd());
    sb1.Append(Separator);
    sb1.Append(input.Substring(SplitPosition + 1).TrimStart());
    sb1.Clear();
}
sw.Stop();
//File write
sw.Reset();
sw.Start();

// Selman Genç StringBuilder    
StringBuilder sb2 = new StringBuilder();
for (int i = 0; i < 1000000; i++)
{
    char? previousChar = null;
    foreach (var ch in input)
    {
        if (ch == ' ' && previousChar == ch) { continue; }
        if (ch == ':' && previousChar != ' ') { sb2.Append(' '); }
        if (previousChar == ':' && ch != ' ') { sb2.Append(' '); }

        sb2.Append(ch);
        previousChar = ch;
    }
    sb2.Clear();
}

sw.Stop();
//File write
sw.Reset();
sw.Start();

for (int i = 0; i < 1000000; i++)
{
    string output = string.Join(" : ", input.Split(':').Select(x => x.Trim()));
}

sw.Stop();

/*(...)
*/
string input=“苹果:100”;
秒表sw=新秒表();
sw.Start();
//计数器测试StringBuilder
StringBuilder sb1=新的StringBuilder();
常量字符串分隔符=“:”;
对于(int i=0;i<1000000;i++)
{
int SplitPosition=input.IndexOf(':');
sb1.Append(input.Substring(0,SplitPosition.TrimEnd());
sb1.追加(分隔符);
sb1.Append(input.Substring(SplitPosition+1.TrimStart());
sb1.Clear();
}
sw.Stop();
//文件写入
sw.Reset();
sw.Start();
//塞尔曼·根萨·斯特林建筑公司
StringBuilder sb2=新的StringBuilder();
对于(int i=0;i<1000000;i++)
{
char?previousChar=null;
foreach(输入中的var ch)
{
如果(ch=''&&previousChar==ch){continue;}
if(ch==':'&&previousChar!=''){sb2.Append('');}
if(previousChar==':'&&ch!=''){sb2.Append('');}
sb2.追加(ch);
previousChar=ch;
}
sb2.Clear();
}
sw.Stop();
//文件写入
sw.Reset();
sw.Start();
对于(int i=0;i<1000000;i++)
{
字符串输出=string.Join(“:”,输入.Split(“:”).Select(x=>x.Trim());
}
sw.Stop();
/*(...)
*/

您考虑的是性能吗?这慢吗?这执行的频率是多少?@trailmax,它执行了很多次。如果我理解你想要的正确,并且它肯定是“1个单词后跟逗号后跟数字”格式,请删除所有空格,然后替换为“:”?但不确定这种方法的性能。将输入拆分一次并将其存储在变量中会使代码更快。没有必要把它拆分两次。@stom我提供了两种解决方案,如果空间在苹果之前,第二种可能不起作用,我留给你来解决:)我觉得名称
lastChar
有点令人不安,因为最后一种也可能意味着终极。
prevChar
不是更合适吗?@PalleDue是的,它更有意义。谢谢你的建议,一个线性是好的:),波斯特说,
Linq
有性能问题,你的建议是什么?@stom Linq并不是天生性能较差的。我不知道你是从哪里得到你的信息的,但这并不准确。LINQ确实容易被误用,我想这可能会导致代码性能下降。@stom我看到了你之前的评论(我正在工作)。如果您认为它可能有用,我可以发布几个比Linq
.Select()
方法性能更好的示例(注意,100万次操作需要几毫秒)。正如我已经提到的,
StringBuilder.Append()
string.Join().Split()性能更好。你可以自己测试。我可以(只要我有时间)发布一个使用
StopWatch()
来测量计时的示例,因为这里已经有很多答案。空格可以在Apple之后或之前,但不能在Apple这个词中。感谢您的工作:)@stom仔细查看计时。我先前所说的并不准确。从可执行文件运行时,提供的@Selman Genç的
StringBuilder
方法性能最好。这与VS环境完全不同,而VS环境正好相反。由于该方法不使用任何“外部”帮助程序(如
Trim()
)的版本),因此它在运行时是最可预测的。总之,当执行字符串连接时,
StringBuilder
是可用的最佳工具