如何恢复删除的空间

时间:2017-07-13 15:00:44

标签: c# string winforms char spaces

我有一个字符串,在单词之间有多个空格,我想删除这些空格,然后把它们带回来..问题是在删除它们之后将空格带回来我尝试编写我的想法但它没有任何运行输出,有时它给我一个例外“索引超出数组范围”..任何帮助

string pt = "My name is Code"
int ptLenght = pt.Length;
char[] buffer1 = pt.ToCharArray();
spaceHolder = new int[pt.Length];
for (int m = 0; m < pt.Length; m++)
{
    if (buffer1[m] == ' ')
    {
        hold = m;
        spaceHolder[m] = hold;
    }
}
char[] buffer = pt.Replace(" ", string.Empty).ToCharArray(); 
int stringRemovedSpaces = pt.Length;
char[] buffer = pt.ToCharArray(); // source
char[] buffer2 = new char[ptLenght]; // destination
for (int i = 0; i < pt.Length; i++)
{
    buffer2[i] = buffer[i];
}
for (int i = 0; i < buffer2.Length; i++)
{
    if (i == spaceHolder[i])
    {
        for (int m = stringRemovedSpaces; m <= i; m--)
        {
            buffer2[m-1] = buffer2[m];
        }
        buffer2[i] = ' ';
    }
}
return new string(buffer2);

3 个答案:

答案 0 :(得分:0)

我怀疑你想用一个空格替换多个空格。最快速,最简单的方法是使用一个简单的正则表达式,用一个空格替换多个空格,例如:

var newString = Regex.Replace("A     B      C",@"[ ]+"," ")

static Regex _spacer = new Regex(@"\s+");


public void MyMethod(string someInput)
{
    ...
    var newString=_spacer.Replace(someInput, " ");
    ...
}

这比其他方法(如重复的字符串替换)最快的原因是正则表达式生成临时字符串。 Internatlly它会生成匹配项的索引列表。仅当代码请求字符串值(如匹配或替换)时才会生成字符串。

正则表达式对象也是线程安全的。您可以创建一次,将其存储在静态字段中并重复使用它:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Datepicker - Format date</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#datepicker" ).datepicker({
dateFormat: "dd-mm-yy"
});
} );
</script>
</head>
<body>

<p>Date: <input type="text" id="datepicker" size="30"></p>


</body>
</html>

答案 1 :(得分:0)

删除字符串中的所有空格实际上就像在字符串上调用Replace函数一样简单。请注意,当您在字符串上调用Replace时,它不会修改原始字符串,它会创建并返回一个新字符串。我之所以提出这个问题是因为你将两个不同的整数变量设置为pt.Length,并且在任何时候都没有实际修改过的字符串pt。另外,我想你会从嵌套的for循环中得到“索引超出数组边界”。您以m将永久递减的方式设置循环。但是,一旦m等于零,您将尝试从buffer2访问索引-1,这是一个否定的。如果要在保留字符串的原始副本的同时删除空格,可以将代码简化为:

string pt = "My name is Code";
string newpt = pt.Replace(" ", string.empty);

pt是一个带空格的字符串,newpt是一个删除了空格的新字符串。但是,如果你想用一个空格替换多个连续的空格,我建议你按照Panagiotis Kanavos给出的答案。

答案 2 :(得分:-1)

我遵循了@maccettura的建议,我这样做了,它按照我的意愿工作:)

 string orignalString = "";
 orignalString = pt;
 char[] buffer = pt.ToCharArray();
 orignalString = new string(buffer);
 return orignalString.Replace(" ", string.Empty);
 // Here I got the string without spaces , now I have the same string with and without spaces
相关问题