我如何从一个字符串复制到另一个字符串从所需的位置到结束

本文关键字:字符串 另一个 结束 位置 复制 一个 | 更新日期: 2023-09-27 18:11:34

假设我有:

string abc="Your name = Hello World";

使用长度函数我匹配=操作符的位置,但是我如何将=之后的所有单词,例如"Hello Word",从这个字符串复制到另一个字符串?

我如何从一个字符串复制到另一个字符串从所需的位置到结束

string abc="Your name = Hello World";
abc.Substring(abc.IndexOf("=")+1); //returns " Hello World"

有几种方法可以做到。这里有几个例子……

使用Split:

string[] parts = abc.Split(new char[]{'='}, 2);
if (parts.Length != 2) { /* Error */ }
string result = parts[1].TrimStart();

使用IndexOfSubstring:

int i = abc.IndexOf('=');
if (i == -1) { /* Error */ }
string s = abc.Substring(abc, i).TrimStart();

使用正则表达式(可能有点夸张):

Match match = Regex.Match(abc, @"='s*(.*)");
if (!match.Success) { /* Error */ }
string result = match.Groups[1].Value;
string newstring = abc.Substring(abc.IndexOf("=") + 2);
    string abc="Your name = Hello World";
    string[] newString = abc.Split('='); 
   /* 
      newString[0] is 'Your name '
      newString[1] is  ' Hello World'
   */