The string is defined by the class, as follows:
1 public sealed class String: IComparable, ICloneable, IConvertible, IComparable <string>, IEnumerable <char>, IEnumerable, IEquatable <string>
Note that it is derived from the IEnumerable <char> interface. If you want to get all single characters, it is easy,
1 List <char> chars = s. ToList ();
If you want to calculate the string, it is also very simple:
1 int cn = s. Count (itm => itm. Equals ('{'));
If you want to reverse the string, as follows:
1 new string (s. Reverse (). ToArray ());
If you traverse the string, you can use the extended method ForEach.
Now there is a requirement. For a list string, I want to replace the string that meets certain conditions and keep the string that does not meet the conditions. The problem is that the string itself cannot be modified during forach. Because msdn has the following descriptions:
A String object is called immutable (read-only) because its value cannot be modified once it has been created. methods that appear to modify a String object actually return a new String object that contains the modification.
The following code constructs two strings:
1 string st = "Hello, world ";
2 st = "Hello, world2 ";
Back to that question, I think a very simple method is to first construct a List <string>, then traverse the original string, modify the conditions, and add a new list, if not, add them directly. This method is simple and original, with the highest efficiency. The keyword "UNION" exists in Linq, and the UNION set operation exists in SQL, so we can solve the problem as follows:
Copy codeThe Code is as follows: private List <String> StringCleanUp (List <string> input)
{
Regex reg = new Regex (@ "\ <(\ w +) \> (\ w + ?) \ </\ 1 \> ", RegexOptions. Singleline );
Var matchItem = (
From c in input
Where reg. IsMatch (c)
Select reg. Replace (c, matchEvaluator)
). Union (
From c in input
Where! Reg. IsMatch (c)
Select c
);
Return matchItem. ToList <string> ();
}
Private string matchEvaluator (Match m)
{
Return m. Groups [2]. Value;
}
The above is a regular expression for matching. If it matches, replace the original information with the information of the matching Group 2. If not, use the original string.
If the problem persists, contact us.