我正在做一些事情,我意识到我想要计算/我能在字符串中找到多少,然后它让我感到震惊,有几种方法可以做到,但无法决定最好的(或最简单的)是什么.
目前我正在做的事情如下:
string source = "/once/upon/a/time/";
int count = source.Length - source.Replace("/", "").Length;
Run Code Online (Sandbox Code Playgroud)
但我完全不喜欢它,任何接受者?
我真的不想挖掘RegEx这个,是吗?
我知道我的字符串将会有我正在搜索的术语,所以你可以认为......
当然,对于字符串,其中 长度> 1,
string haystack = "/once/upon/a/time";
string needle = "/";
int needleCount = ( haystack.Length - haystack.Replace(needle,"").Length ) / needle.Length;
Run Code Online (Sandbox Code Playgroud) 我需要帮助创建一个C#方法,它返回字符串中第N个字符出现的索引.
例如,'t'字符串中第3次出现的字符"dtststxtu"是5.
(注意字符串有4 t秒.)
如何删除字符串中的前n行?
例:
String str = @"a
b
c
d
e";
String output = DeleteLines(str, 2)
//Output is "c
//d
//e"
Run Code Online (Sandbox Code Playgroud) 我有一个字符串,其中可能包含两次"title1".
例如
server/api/shows?title1 =它在费城总是阳光充足&title1 =破坏...
我需要将单词"title1"的第二个实例更改为"title2"
我已经知道如何识别字符串中是否有两个字符串实例.
int occCount = Regex.Matches(callingURL, "title1=").Count;
if (occCount > 1)
{
//here's where I need to replace the second "title1" to "title2"
}
Run Code Online (Sandbox Code Playgroud)
我知道我们可以在这里使用Regex但是我无法在第二个实例上获得替换.任何人都可以帮我一把吗?
我有一个输入字符串如下:
thumb_634735515600845357tchayat_november_200612.jpg
Run Code Online (Sandbox Code Playgroud)
我想要做的是首先拆分这个字符串_.然后将得到的标记放在1到n的位置并加入它们.
具体来说,就我的样本输入而言,这是我想要的输出.如您所见,thumb_已从字符串的前面删除:
634735515600845357tchayat_november_200612.jpg
Run Code Online (Sandbox Code Playgroud)
我知道怎么做分裂.但接下来我该如何进行加入步骤呢?我意识到我可以使用for循环来进行连接.但有更好的方法吗?我不能使用子字符串方法来执行连接步骤,因为我之前有数据thumb_.
最后,请注意,后面的_字符thumb始终是第一个实例_.
我注意到一个 小 问题,关于寻找字符串中的字符的第n次出现.由于我很好奇(并且在应用程序中有多种用途,但主要是出于好奇),我在Visual Studio 2010中对这些方法中的两个进行了编码和基准测试,我想知道为什么方法1(FindNthOccurrence)比方法慢得多2(IndexOfNth).我能想到的唯一原因是:
indexOf是一个内置的.NET方法,因此已经过优化我倾向于#2,但我仍然想知道.这是相关的代码.
class Program
{
static void Main(string[] args)
{
char searchChar = 'a';
Random r = new Random(UnixTimestamp());
// Generate sample data
int numSearches = 100000, inputLength = 100;
List<String> inputs = new List<String>(numSearches);
List<int> nth = new List<int>(numSearches);
List<int> occurrences = new List<int>(numSearches);
for (int i = 0; i < numSearches; i++)
{
inputs.Add(GenerateRandomString(inputLength, "abcdefghijklmnopqrstuvwxyz"));
nth.Add(r.Next(1, 4));
}
// Timing of FindNthOccurrence …Run Code Online (Sandbox Code Playgroud)