在C#中拆分字符串,为什么这不起作用?

时间:2013-07-06 19:23:53

标签: c# text

我有以下字符串:

  

string myString =“测试的目标。\ vVision \ v *提供测试   目标\ v **全面\ v **控制\ v *与跨股权对齐   strategy \ vApproach \ v *加速“

我试图拆分“\ v”

我试过了,但它似乎不起作用:

char[] delimiters = new char[] { '\v' };
string[] split = myString.Split(delimiters);
for (int i = 0; i < split.Length; i++) {
} 

split.Length显示为1.有任何建议吗?

4 个答案:

答案 0 :(得分:5)

"\v"是原始字符串中的两个字符,而不是一个字符(不会将\计为转义字符,就像文字C#字符串一样)。

你需要在文字"\v"上拆分,这意味着你需要指定带有字符串的Split的重载:

string[] split = narrative.Split(new string[] {"\\v"}, StringSplitOptions.None);

请注意我必须使用“\\”

转义“\”字符

您的'\v'是一个控制字符,而不是两个字符。

我认为你的问题本身有点误导......

您的示例字符串,如果输入C#,实际上会按预期工作,因为verbatum C#字符串中的\v将转义为特殊字符:

string test = " The objective for test.\vVision\v* Deliver a test goals\v** Comprehensive\v** Control\v* Alignment with cross-Equities strategy\vApproach\v*An acceleration ";

char[] delimiters = new char[] { '\v' };
Console.WriteLine(test.Split(delimiters).Length); // Prints 8

但是,我认为你的实际字符串确实有反斜杠-v而不是转义\ v:

string test = " The objective for test.\\vVision\\v* Deliver a test goals\\v** Comprehensive\\v** Control\\v* Alignment with cross-Equities strategy\\vApproach\\v*An acceleration ";

char[] delimiters = new char[] { '\v' };
Console.WriteLine(test.Split(delimiters).Length); // Prints 1, like you say you see.

因此,您可以通过使用字符串数组来拆分字符串来解决上述问题:

string test = " The objective for test.\\vVision\\v* Deliver a test goals\\v** Comprehensive\\v** Control\\v* Alignment with cross-Equities strategy\\vApproach\\v*An acceleration ";

string[] delimiters = new [] { "\\v" };
Console.WriteLine(test.Split(delimiters, StringSplitOptions.None).Length); // Prints 8

答案 1 :(得分:0)

使用类似的东西

string[] separators = {@"\v"};
      string value = @"The objective for test.\vVision\v* Deliver a test goals\v** Comprehensive\v** Control\v* Alignment with cross-Equities strategy\vApproach\v*An acceleration";
      string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);

答案 2 :(得分:-1)

像这样使用,

string myString = " The objective for test.\vVision\v* Deliver a test goals\v** Comprehensive\v** Control\v* Alignment with cross-Equities strategy\vApproach\v*An acceleration";
string[] delimiters = new string[] { "\v" };
string[] split = myString.Split(delimiters, StringSplitOptions.None);
for (int i = 1; i < split.Length; i++)
{
}

答案 3 :(得分:-1)

如果您不需要生成的数组供以后使用,可以将split和loop组合成一个调用。

foreach (string s in myString.Split(new[] { "\v" }, StringSplitOptions.RemoveEmptyEntries))
{
   //s is the string you can now use in your loop
}