从 C# 中的字符串中选择子字符串 [英] Selecting a substring from a string in C#

查看:56
本文介绍了从 C# 中的字符串中选择子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在字符串中找到一个字符串.

I am looking to find a string with in a string.

假设我有 2 个字符串:

Lets say I have 2 strings:

String1 = "1.1)The Element is"

String2 = "1.1)The Element is:(-) for the sub"

如果我将 String1 与 String2 进行比较,我可以得到 "1.1)The Element is" 这没问题.

If I compare String1 with String2, I can get "1.1)The Element is" which is ok.

 int Length_Str1 = string1.Length;

 string2 = string2.Remove(Length_Str1);

但我也想获得非字母字符:(-)".我想继续提取字符,直到找到空格字符.但我不知道如何在 C# 中做到这一点.

But I also want to get the non-alphabetical characters ":(-)". I am thinking to keep extracting the character until a space character is found. But I don't know how I can do it in C#.

推荐答案

只要 Char.IsLetterChar.IsWhiteSpace 返回 false,你就可以取字符:

You could take chars so long as Char.IsLetter and Char.IsWhiteSpace return false:

int index = String2.IndexOf(String1);
if(index >= 0)
{
    string result = String1;
    if (String1.Length < String2.Length)
    {
        string rest = String2.Substring(index + String1.Length);
        var chars = rest.TakeWhile(c => !Char.IsLetter(c) && !Char.IsWhiteSpace(c));
        result = result + string.Join("", chars);
    }
}

请注意,您必须在文件顶部添加using System.Linq;.

Note that you have to add using System.Linq; at the top of the file.

这篇关于从 C# 中的字符串中选择子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆