C# 获取字符串中某个索引后第一个检测到的空间的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15831171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get index of first detected space after a certain index in a string
提问by Indigo
In a string to format (mostly to replace chars with different symbols for rendering test on UI), I have to detect % and then skip all chars util first space from this % char and it has to be repeated for all instances in the string.
在要格式化的字符串中(主要是用不同的符号替换字符以在 UI 上进行渲染测试),我必须检测 % 然后从这个 % 字符中跳过所有字符 util 第一个空格,并且必须对字符串中的所有实例重复它。
E.g.abcd%1$s efgh %2$d ijkl
.In this string, I have to get index of % and then find index of first space from that. Basically, I have to skip this %1$s
& %2$d
which are some sort of formatting placeholders. I hope, I am not putting it in complex way here.
例如abcd%1$s efgh %2$d ijkl
。在这个字符串中,我必须得到 % 的索引,然后从中找到第一个空格的索引。基本上,我必须跳过这个%1$s
&%2$d
这是某种格式占位符。我希望,我不会在这里用复杂的方式来表达它。
采纳答案by Mike Perrenoud
You can get that pretty easily, just grab the index if the first percent sign and then leverage that index to find the first space from there:
你可以很容易地得到它,只要抓住第一个百分号的索引,然后利用该索引从那里找到第一个空格:
var start = myString.IndexOf("%");
var spaceIndex = myString.IndexOf(" ", start)
of course the value of myString is the string you represented in your question.
当然 myString 的值是您在问题中表示的字符串。
回答by prassie
Following is easiest, and extensible, for your requirement "abcd%1$s efgh %2$d ijkl
in this string I have to skip this %1$s
& %2$d
which are some sort of formatting placeholders."
以下是最简单且可扩展的,对于您的要求“abcd%1$s efgh %2$d ijkl
在此字符串中,我必须跳过此%1$s
&%2$d
是某种格式占位符。”
string[] placeHolders = new string[] {"%1$s", "%2$d"};
string[] splits = "abcd%1$s efgh %2$d ijkl".Split(placeHolders, StringSplitOptions.None);
which will provide splits
as ["abcd", "efgh", "ijkl"]
这将提供splits
作为["abcd", "efgh", "ijkl"]