我創建了一個人模型:
Model Person = new Model();
Person.LastName = values[0];
[LastName 是一個字串]
我想用另一個字串值(如“ Frank ”)替換值 [0],即“ Anna ”,如果它包含雙字符,在這種情況下,“如果Anna包含雙字符,請更改值用另一個字串”。
怎么做?
uj5u.com熱心網友回復:
撰寫一個輔助函式來測驗連續相等的字符:
private static bool HasDoubleCharacter(string s)
{
char? previous = null;
foreach (char ch in s) {
if (ch == previous) {
return true;
}
previous = ch;
}
return false;
}
你可以寫
Model Person = new Model();
string name = values[0];
if (HasDoubleCharacter(name)) {
name = "Frank";
}
Person.LastName = name;
您還可以創建一個僅包含不帶雙字符的名稱的新陣列,并改用該陣列:
Model Person = new Model();
string[] names = values
.Where(v => !HasDoubleCharacter(v))
.ToArray();
if (names.Length > 0) {
Person.LastName = names[0];
}
uj5u.com熱心網友回復:
public static string Do(string source, string replacement)
{
char c = source.ToLower()[0]; // do you care about case? E.g., Aaron.
for(int i = 1; i < source.Length; i )
{
if (source.ToLower()[i] == c)
{
return replacement;
}
}
return source;
}
public static void Main()
{
string thing = "Aaron";
thing = Do(thing, "Frank");
}
uj5u.com熱心網友回復:
與Micha? Turczyn帖子中的想法相同- 檢查雙字符,但通過正則運算式實作:
using System.Text.RegularExpressions;
...
public static bool HasDoubleChar(string value) =>
value != null && Regex.IsMatch(value, @"(.)\1");
模式(.)\1解釋:
(.) - group which contains an arbitrary character
\1 - the group #1 repeated again
請注意,我們在這里有一些靈活性:(\p{L})\1將只檢查雙字母,而不是空格;(?i)(.)\1將比較忽略大小寫(Aaron將被匹配)等。
然后像往常一樣
Person.LastName = HasDoubleChar(values[0])
? "Frank"
: values[0];
uj5u.com熱心網友回復:
這可以通過字串的簡單擴展功能來實作:
public static class StringExtensions
{
public static bool HasDoubleChar(this string @this)
{
ArgumentNullException.ThrowIfNull(@this);
for (int i = 1; i < @this.Length; i )
{
if (@this[i] == @this[i - 1])
{
return true;
}
}
return false;
}
}
然后你可以使用它:
Person.LastName = values[0].HasDoubleChar()
? "Frank"
: values[0];
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/520197.html
標籤:C#。网视觉工作室哎呀
