简体   繁体   English

从C#中的字符串中选择子字符串

[英]Selecting a substring from a string in C#

I am looking to find a string with in a string. 我正在寻找在字符串中找到一个字符串。

Lets say I have 2 strings: 可以说我有2个字符串:

String1 = "1.1)The Element is"

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

If I compare String1 with String2, I can get "1.1)The Element is" which is ok. 如果将String1与String2进行比较,可以得到“ 1.1)The Element is” ,这是可以的。

 int Length_Str1 = string1.Length;

 string2 = string2.Remove(Length_Str1);

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#. 但是我不知道如何在C#中做到这一点。

You could take chars so long as Char.IsLetter and Char.IsWhiteSpace return false : 只要Char.IsLetterChar.IsWhiteSpace返回false就可以使用chars:

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);
    }
}

Note that you have to add using System.Linq; 注意,您必须using System.Linq;添加using System.Linq; at the top of the file. 在文件的顶部。

How about this: 这个怎么样:

string s = "1.1)The Element is:(-) for the sub";
s = s.Substring(0, s.IndexOf("(-) ") + "(-) ".Length);

This gives 1.1)The Element is:(-) 这给出1.1)The Element is:(-)

string s = "1.1)The Element is:(-) for the sub";
s = s.Substring(s.IndexOf("(-) ") + "(-) ".Length);

This gives for the sub . 这给for the sub Going by your comment: 根据您的评论:

 string String1 = "1.1)The Element is";

 string String2 = "1.1)The Element is:(-) for the sub";
 if(String2.Contains(String1))
 {
      string s = String2.Substring(String2.IndexOf(String1)+ String1.Length);
      s = s.Substring(s.IndexOf(" ")+1);  // +1 to leave space
 }
var String1 = "1.1)The Element is";
var String2 = "1.1)The Element is:(-) for the sub";
var result = string.Empty;
if(String2.Contains(String1))
{
    result = String1 + Regex.Match(String2.Replace(String1, string.Empty), "[^\\sa-zA-Z0-9]+").ToString();
}

//result will contain String1 + ":(-)" from String2 IF there is a match

This could be solved with a regular expression quite easily: 可以很容易地用正则表达式解决:

//Note the special escape character here for the regex engine not to fail on a found ')'
string string1 = @"1.1\)The Element is:";

List<string> testStrings = new List<string>();
testStrings.Add(@"1.1)The Element is:(-) for the sub 1");
testStrings.Add(@"1.1)The Element is:) for the sub 2");
testStrings.Add(@"1.1)The Element is:[-] for the sub 3");

//Create a regular expression string based upon the 'string1' provided above.
string regularExpression = string.Format(@"(?<base>{0})+(?:[^\\sa-zA-Z0-9]+)", string1);
Regex regex = new Regex(regularExpression, RegexOptions.Multiline);
//Will contain the found results
List<string> subStrings = new List<string>();

foreach (string str in testStrings)
{
  foreach (Match match in regex.Matches(str))
  {
    if (match.Success)
    {
      subStrings.Add(str.Replace(match.Groups[0].ToString(), string.Empty));
    }
  }
}
//Display the found results
foreach (string str in subStrings)
{
  Console.WriteLine(str);
}

After executing this code, it will yield the following results: 执行此代码后,它将产生以下结果:

for the sub 1 
for the sub 2 
for the sub 3

I am not sure if this is what you are looking for, but this code makes it able to have different patterns after 'is:'. 我不确定这是否是您要查找的内容,但是此代码使它能够在“ is:”之后具有不同的模式。

Edit: Hash Sling Slasher just provided the same answer, albeit a bit smaller :) 编辑: Hash Sling Slasher只是提供了相同的答案,尽管稍小:)

How about using Split and string.Join like this ? 如何使用Splitstring.Join这样加入?

var str1 = "1.1)The Element is";
var str2 = "1.1)The Element is:(-) for the sub";

str2 = string.Join(" ",str2.Split().Take(str1.Count(x => x == ' ')+1));

You can do something like: 您可以执行以下操作:

At least if your string is always with the same format ;) 至少如果您的字符串始终具有相同的格式;)

string result = string.Join(" ", string1.Split(' ').Take(3).ToArray<string>());

I hope this helps 我希望这有帮助

The following code should find the index of the first space after the length of string1. 以下代码应在string1长度之后找到第一个空格的索引。

int Length_Str1 = string1.Length;

string2 = string2.Remove(string2.IndexOf(' ', Length_Str1));

Please note that you should also add some checks to make sure that string2 is longer than string1 and that .IndexOf actually finds a space. 请注意,您还应该添加一些检查以确保string2比string1长,并且.IndexOf实际上找到一个空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM