如何在C#中获取字符串的子串?

24

我有一个大字符串,存储在一个字符串变量中,str。我想在C#中从该字符串中获取子串。

假设字符串是:" Retrieves a substring from this instance. The substring starts at a specified character position, "

我想要显示的子串结果是:The substring starts at a specified character position.


3
为什么要使用Substring?也许有更好的方法来实现你所需的功能,而不是用一个魔数和Substring。但由于你还没有告诉我们你的主要目标是什么,所以很难建议更好的方法。 - Mark Byers
10个回答

28

你可以手动完成这个操作,或者使用IndexOf方法。

手动:

int index = 43;
string piece = myString.Substring(index);
使用IndexOf方法,您可以查看句号(full stop)的位置:
int index = myString.IndexOf(".") + 1;
string piece = myString.Substring(index);

+1 还提出了一种不使用魔数的方法。但实际上,问题不清楚需要做什么以及为什么。 - Mark Byers
1
我建议使用 int index = 1+myString.IndexOf(".");string piece = myString.Substring(index); 来省略掉'.'。 - Harsh Baid

23
string newString = str.Substring(0, 10);

这将会给你字符串的前10个字符 (从位置0到位置9)。

参见String.Substring方法


从网站上摘录。如果我想要第1025个字符和从那里开始的下一个1024块怎么办? - Ken

4
这里有一个示例,可以从第14个字符截取到字符串末尾。你可以根据自己的需要进行修改。
string text = "Retrieves a substring from this instance. The substring starts at a specified character position.";

// Get substring where 14 is the start index
string substring = text.Substring(14);

adrian,抱歉我通常不会轻易地给出反对意见,但在这种情况下我不得不这样做。不仅存在一定的“不安全性”,而且您也没有提供任何逻辑解释为什么选择了神奇数字14(实际上这会导致我们得到“string from this...”)。我就是不明白。再次抱歉,但我觉得我必须指出这一点。 - jim tollan
14只是一个随机数,我觉得我不应该为Riya计算字符串的字符数,他可能可以自己做到...我的答案只是获取字符串一部分的示例,我并不打算提供完整的解决方案。在我看来,对于这样简单的问题,指出正确的方向比提供完整的代码更好,以防止抄袭... - Adrian Serafin
1
Adrian - 我的不满是基于问题明确要求:子字符串结果我想显示为:“子字符串从指定字符位置开始。”因此,除了将子字符串视为对问题的字面解释之外,我无法看到你回答中的相关性。话虽如此,我理解你提供指导而非完整答案的观点。祝一切顺利。 - jim tollan
好的,我已经编辑了我的答案,以便清楚地表明这只是使用子字符串的示例 :) - Adrian Serafin

2
假设您想在句号(.)处拆分,那么这是一种可以捕获所有出现情况的方法:
// Add @ to the string to allow split over multiple lines
// (for display purposes to save the scroll bar from 
// appearing on a Stack Overflow question :))
string strBig = @"Retrieves a substring from this instance.
            The substring starts at a specified character position. great";

// Split the string on the full stop, if it has a length>0
// then, trim that string to remove any undesired spaces
IEnumerable<string> subwords = strBig.Split('.')
    .Where(x => x.Length > 0).Select(x => x.Trim());

// Iterate around the new 'collection' to sanity check it
foreach (var subword in subwords)
{
    Console.WriteLine(subword);
}

2

C# 8中使用索引的更好解决方案:

string s = " Retrieves a substring from this instance. The substring starts at a specified character position, ";

string subString = s[43..^2]; // The substring starts at a specified character position

1
string text = "Retrieves a substring from this instance. The substring starts at a specified character position. Some other text";

string result = text.Substring(text.IndexOf('.') + 1,text.LastIndexOf('.')-text.IndexOf('.'))

这将剪切位于特殊字符之间的字符串部分。

0
var data =" Retrieves a substring from this instance. The substring starts at a specified character position.";

var result = data.Split(new[] {'.'}, 1)[0];

输出:

从此实例检索子字符串。子字符串从指定的字符位置开始。


0

所有答案都使用了降低性能的主字符串。您应该使用Span以获得更好的性能:

var yourStringSpan = yourString.AsSpan();
int index = yourString.IndexOf(".") + 1;
string piece = yourStringSpan.slice(index);

0

只是想知道经过这么多年后是否有人在寻找这个.. 你可以通过这行代码从字符串中获取所需的子串。

string text = "Retrieves a substring from this instance. The substring starts at a specified character position, ";
text = text.Substring(text.IndexOf('.') + 1);

-2

在C#中重写这段代码很容易...

Enter image description here

如果您的值在两个子字符串之间,此方法将起作用!

例如:

stringContent = "[myName]Alex[myName][color]red[color][etc]etc[etc]"

调用应该是:

myNameValue = SplitStringByASubstring(stringContent, "[myName]")

colorValue = SplitStringByASubstring(stringContent, "[color]")

etcValue = SplitStringByASubstring(stringContent, "[etc]")

2
首先,您应该将您的代码作为文本发布,图片可能会出现链接错误,无法搜索。其次,如果您认为您的答案是正确的,您应该使用OP的示例。 - Prisoner

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