从字符串中获取特定字符后的字符

3
我需要在字符串中找到某个字符匹配后的字符。请考虑我的输入字符串和预期结果字符集。 样例字符串
*This is a string *with more than *one blocks *of values.

结果字符串
Twoo

我已经做了这件事。
string[] SubIndex = aut.TagValue.Split('*');
            string SubInd = "";
            foreach (var a in SubIndex)
            {
                SubInd = SubInd + a.Substring(0,1);
            }

任何对此的帮助将不胜感激。
谢谢。

2
你目前想到了什么? - Roy Dictus
1
这个字符串怎么样:“** *** ***** lol” - astef
@astef:对于这个字符串 "** *** ***** lol",应该返回空字符串(即 "")。 - DonMax
1
@DonMax:为什么"** *** ***** lol"应该是空的?根据你当前的规则,它应该是" "(3个空格)。 - musefan
你的代码有什么问题? - Kuzgun
6个回答

5

LINQ解决方案:

var str = "*This is a string *with more than *one blocks *of values.";
var chars = str.Split(new char[] {'*'}, StringSplitOptions.RemoveEmptyEntries)
               .Select(x => x.First());
var output = String.Join("", chars);

请注意,如果字符串的第一个字符不是“*”,它仍将包含在输出中。 - Brian

3
string s = "*This is a string *with more than *one blocks *of values.";
string[] splitted = s.Split(new char[] { '*' }, StringSplitOptions.RemoveEmptyEntries);
string result = "";
foreach (string split in splitted)
    result += split[0];
Console.WriteLine(result);

不需要进行“IsNullOrEmpty”验证,由于使用了“RemoveEmptyEntries”标志,split永远不会为空。 - musefan

2
以下代码应该可以工作。
var s = "*This is a string *with more than *one blocks *of values."
while ((i = s.IndexOf('*', i)) != -1)
{
    // Print out the next char
    if(i<s.Length)
            Console.WriteLine(s[i+1]);

    // Increment the index.
    i++;
}

1
String.Join("",input.Split(new char[]{'*'},StringSplitOptions.RemoveEmptyEntries)
                    .Select(x=>x.First())
           );

你尝试使用示例字符串了吗?由于空字符串,你会得到一个异常。 - Tim Schmelter

0
请看下面...
char[] s3 = "*This is a string *with more than *one blocks *of values.".ToCharArray();
StringBuilder s4 = new StringBuilder();
for (int i = 0; i < s3.Length - 1; i++)
{
   if (s3[i] == '*')
     s4.Append(s3[i+1]);
}
Console.WriteLine(s4.ToString());

0
string strRegex = @"(?<=\*).";
Regex myRegex = new Regex(strRegex, RegexOptions.Multiline | RegexOptions.Singleline);
string strTargetString = "*This is a string *with more than *one blocks *of values.";
StringBuilder sb = new StringBuilder();    
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
    if (myMatch.Success) sb.Append(myMatch.Value);
}
string result = sb.ToString();

为什么每当有人需要字符串解析时,总会有人提出正则表达式的解决方案? - musefan
在某些情况下可能需要更多的灵活性。对于这个简单的任务来说,可能有点过头了... - Vojtěch Dohnal
是的,有一些情况...但这个问题不是“我如何为其他情况做某事”。这个问题明确了要求,而正则表达式并不是一个好的解决方案。 - musefan
好的,但我主要将这个网站用作知识库,使用已经回答的问题。这可能对其他人有用。 - Vojtěch Dohnal
是的,这个网站旨在为未来的访问者提供帮助。但我认为,在不适当的情况下鼓励使用正则表达式并不是有益的。 - musefan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接