简体   繁体   English

转到字符串中的每个空白。 C#

[英]Go to each white space in a string. C#

Is it possible to pass over a string, finding the white spaces? 是否可以通过字符串,找到空白?

For example a data set of: 例如一个数据集:

string myString = "aa bbb cccc dd";

How could I loop through and detect each white space, and manipulate that space? 我该如何遍历并检测每个空白并操纵该空白?

I need to do this in the most effecient way possible. 我需要以最有效的方式做到这一点。

Thanks. 谢谢。

UPDATE: 更新:
I need to manipulate the space by increasing the white space from an integer value. 我需要通过从整数值增加空白来操纵空间。 So for instance increase the space to have 3 white spaces instead of one. 因此,例如将空间增加为3个空格,而不是1个。 I'd like to make it go through each white space in one loop, any method of doing this already in .NET? 我想让它在一个循环中遍历每个空白,.NET中已经有这样做的任何方法了吗? By white space I mean a ' '. 空格表示“”。

You can use the Regex.Replace method. 您可以使用Regex.Replace方法。 This will replace any group of white space character with a dash: 这将用破折号替换任何一组空格字符:

myString = Regex.Replace(myString, "(\s+)", m => "-");

Update: 更新:

This will find groups of space characters and replace with the tripple amount of spaces: 这将找到一组空格字符,并用三倍的空格代替:

myString = Regex.Replace(
  myString,
  "( +)",
  m => new String(' ', m.Groups[1].Value.Length * 3)
);

However, that's a bit too simple to make use of regular expressions. 但是,使用正则表达式有点太简单了。 You can do the same with a regular replace: 您可以使用常规替换执行以下操作:

myString = myString.Replace(" ", "   ");

This will replace each space intead of replace groups of spaces, but the regular replace is much simpler than Regex.Replace , so it should still be at least as fast, and the code is simpler. 这将替换替换空间组中的每个空间,但是常规替换比Regex.Replace简单得多,因此它至少应该同样快,并且代码也更简单。

If you want to replace all whitespace in one swoop, you can do: 如果要一键替换所有空格,可以执行以下操作:

// changes all strings to dashes
myString.Replace(' ', '-');

If you want to go case by case (that is, not just a mass replace), you can loop through IndexOf() : 如果要逐例处理(即不只是批量替换),可以遍历IndexOf()

int pos = myString.IndexOf(' ');

while (pos >= 0)
{
    // do whatever you want with myString @ pos

    // find next
    pos = myString.IndexOf(' ', pos + 1);
}

UPDATE 更新

As per your update, you could replace single spaces with the number of spaces specified by a variable (such as numSpaces ) as follows: 根据您的更新,您可以将单个空格替换为变量指定的空格数(例如numSpaces ),如下所示:

myString.Replace(" ", new String(' ', numSpaces));

Depending on what you're tring to do: 根据您要执行的操作:

for(int k = 0; k < myString.Length; k++)
{
   if(myString[k].IsWhiteSpace())
   {
       // do something with it
   }
}

The above is a single pass through the string, so it's O(n). 上面是对字符串的单次传递,因此为O(n)。 You can't really get more efficient that that. 您真的无法获得更高的效率。

However, if you want to manipulate the original string your best bet is to Use a StringBuilder to process the changes: 但是,如果要操纵原始字符串,最好的选择是使用StringBuilder处理更改:

StringBuilder sb = new StringBuilder(myString);
for(int k = 0; k < myString.Length; k++)
{
   if(myString[k].IsWhiteSpace())
   {
       // do something with sb
   }
}

Finally, don't forget about Regular Expressions. 最后,不要忘记正则表达式。 It may not always be the most efficient method in terms of code run-time complexity but as far as efficiency of coding it may be a good trade-off. 就代码运行时复杂性而言,它可能并不总是最有效的方法,但就编码效率而言,这可能是一个不错的权衡。

For instance, here's a way to match all white spaces: 例如,这是一种匹配所有空格的方法:

var rex = new System.Text.RegularExpressions.Regex("[^\\s](\\s+)[^\\s]");
var m = rex.Match(myString);
while(m.Success)
{
    // process the match here..

    m.NextMatch();
}

And here's a way to replace all white spaces with an arbitrary string: 这是用任意字符串替换所有空格的一种方法:

var rex = new System.Text.RegularExpressions.Regex("\\s+");
String replacement = "[white_space]";
// replaces all occurrences of white space with the string [white_space]
String result = rex.Replace(myString, replacement);

If you just want to replace all spaces with some other character: 如果只想用其他字符替换所有空格:

myString = myString.Replace(' ', 'x');

If you need the possibility of doing something different to each: 如果您需要对每种方法做一些不同的事情:

foreach(char c in myString)
{
    if (c == ' ')
    {
        // do something
    }
}

Edit: 编辑:

Per your comment clarifying your question: 根据您的评论澄清您的问题:

To change each space to three spaces, you can do this: 要将每个空格更改为三个空格,可以执行以下操作:

myString = myString.Replace(" ", "   ");

However note that this doesn't take into account instances where your input string already has two or more spaces. 但是请注意,这并未考虑输入字符串中已经有两个或多个空格的实例。 If that is a possibility you will want to use a regex. 如果可能的话,您将要使用正则表达式。

LINQ query below returns a set of anonymous type items with two properties - "sybmol" represents a white space character, and "index" - index in the input sequence. 下面的LINQ查询返回一组具有两个属性的匿名类型项-“ sybmol”代表空格字符,“ index”-输入序列中的索引。 After that you have all whitespace characters and a position in the input sequence, now you can do what you want with this. 之后,您将拥有所有空格字符和输入序列中的位置,现在您可以执行此操作。

string myString = "aa bbb cccc dd";
var res = myString.Select((c, i) => new { symbol = c, index = i })
                  .Where(c => Char.IsWhiteSpace(c.symbol));

EDIT: For educational purposes below is implementation you are looking for, but obviously in real system use built in string constructor and String.Replace() as shown in other answers 编辑:出于教育目的,下面是您要寻找的实现,但是显然在实际系统中,使用内置在字符串构造函数和String.Replace()中的其他答案所示

string myString = "aa bbb cccc dd";
var result = this.GetCharacters(myString, 5);
string output = new string(result.ToArray());


public IEnumerable<char> GetCharacters(string input, int coeff)
{
    foreach (char c in input)
    {
        if (Char.IsWhiteSpace(c))
        {
            int counter = coeff;
            while (counter-- > 0)
            {
                yield return c;
            }
        }
        else
        {
            yield return c;
        }
    }
}
var result = new StringBuilder();

foreach(Char c in myString)
{
   if (Char.IsWhiteSpace(c))
   {
       // you can do what you wish here. strings are immutable, so you can only make a copy with the results you want... hence the "result" var.

      result.Append('_'); // for example, replace space with _
   }
   else result.Append(c);

}

myString = result.ToString();

If you want to replace the white space with, eg '_', you can using String.Replace . 如果要将空格替换为“ _”,则可以使用String.Replace

Example: 例:

string myString = "aa bbb cccc dd";
string newString = myString.Replace(" ", "_"); // gives aa_bbb_cccc_dd

使用string.Replace()

string newString = myString.Replace(" ", "   ");

In case you want to left/right justify your string 如果您想left/right justify您的字符串

int N=10;
string newstring = String.Join(
        "",
        myString.Split(' ').Select(s=>s.PadRight(N-s.Length)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM