![](/img/trans.png)
[英]How can I repeat a character to make up a string if I have a number for the times to repeat?
[英]Can I limit the number of times a character appears in a string?
例如,我有一個字符串,我只希望字符“ <”在字符串中出現10次,並創建一個子字符串,其中截止點是該字符的第10個出現位置。 這可能嗎?
手動解決方案可能如下所示:
class Program
{
static void Main(string[] args)
{
int maxNum = 10;
string initialString = "a<b<c<d<e<f<g<h<i<j<k<l<m<n<o<p<q<r<s<t<u<v<w<x<y<z";
string[] splitString = initialString.Split('<');
string result = "";
Console.WriteLine(splitString.Length);
if (splitString.Length > maxNum)
{
for (int i = 0; i < maxNum; i++) {
result += splitString[i];
result += "<";
}
}
else
{
result = initialString;
}
Console.WriteLine(result);
Console.ReadKey();
}
}
順便說一句,嘗試使用Regex進行操作可能會更好(以防將來可能有其他替換規則,或者需要進行更改等)。 但是,鑒於您的問題,類似的方法也將起作用。
您可以將TakeWhile
用於您的目的,給定字符串s
,字符<
as c
,count 10
作為count
,以下函數可以解決您的問題:
public static string foo(string s, char c, int count)
{
var i = 0;
return string.Concat(s.TakeWhile(x => (x == c ? i++ : i) < count));
}
Regex.Matches可用於計算字符串中振作的次數。
它還引用每個事件的位置,即Capture.Index屬性。
您可以讀取Nth
事件的索引並在其中剪切字符串:
( RegexOptions
,以防萬一模式有所不同。根據需要進行修改。)
int cutAtOccurrence = 10;
string input = "one<two<three<four<five<six<seven<eight<nine<ten<eleven<twelve<thirteen<fourteen<fifteen";
var regx = Regex.Matches(input, "<", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
if (regx.Count >= cutAtOccurrence) {
input = input.Substring(0, regx[cutAtOccurrence - 1].Index);
}
現在input
:
one<two<three<four<five<six<seven<eight<nine<ten
如果您需要多次使用此過程,則最好構建一個返回StringBuilder
的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.