为什么总是在结尾处将空字符串[非空白]添加到字符串变量中? [英] why always the empty string[Not White space] is added to the string variable at the end ?

查看:96
本文介绍了为什么总是在结尾处将空字符串[非空白]添加到字符串变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ex,
字符串str ="Hai";
逐行执行并检查str持有什么(选择整个内容(cntl + A),然后在字母i后面查看)

ex,
string str = "Hai";
Do line by line execution and check what str holds(Select the whole thing (cntl + A) and See after the letter i)

推荐答案

如何添加空字符串到一个字符串?

如果您的字符串中包含某些内容,则您永远不会看到一个空字符串作为该字符串的一部分.

认为您错过了了解某些东西的机会.

在上面的代码中,如果您停止行中执行string str="Hai";,那么直到通过此行之前,str = empty.string可能不会分配给该行之后的"Hai" .
如果您在此行后立即添加断点并查看变量str 将等于"Hai".


参见下面的代码;它将测试String.Empty的字符串,以及第一个已知字符"a"的位置;您会看到头寸位置恢复原状.这不是在任何地方添加String.empty的情况,这只是系统处理"nothing"的方式;

How can empty string be added to a a string?

if your string has something in it, then you can never see an empty string as part of the string.

Think you are miss understanding something.

In the code above if you stop the execution on the line, string str="Hai";, then it is possible that str = empty.string until after this line as "Hai" will not be assigned until you pass through this line.
if you add a breakpoint immediately after this line and look at the variables str will equal "Hai".


See the following code; it will test a string for String.Empty, and also for the position of the first known character ''a''; you will see that position positions come back the same. It is not a case of a String.empty being added anywhere, it is just how the system deals with ''nothing'';

string str = "aaa";
//Test 1
if (str.Contains(String.Empty))
    MessageBox.Show("String aaa contains an empty string");
//Test 2
int pos = str.IndexOf(String.Empty);
int pos2 = str.IndexOf("a");

//Feedback
MessageBox.Show("String.Empty at Position: " + pos.ToString());
MessageBox.Show("First 'a' is at Position: " + pos.ToString());
MessageBox.Show("The 2 position index match: " + (pos == pos2));


String.Empty不会附加到原始字符串,您看到的是split函数的结果,该函数认识到要分割的字符位于字符串的结尾.

如果您不希望这样做,则只需使用StringSplitOptions.RemoveEmptyEntries选项.

String.Empty isn''t appended to the original string, what your seeing is the result of the split function recognising that the character you want to split by is at the end of the string.

If you don''t want it to do this simply use the StringSplitOptions.RemoveEmptyEntries option.

string str = "aaa"; 
str += "*"; 
string[] Ss = str.Split(new char[]{'*'}, StringSplitOptions.RemoveEmptyEntries);
int a = Ss.Length; 
Response.Write(a); 
if(Ss[1] == string.Empty) Response.Write("Empty string is there....");  



当然,由于Ss只有1个元素长,因此最后一行现在将引发异常.



Of course, the last line will now throw an exception as Ss is only 1 element long.


是的只有在split的最后一个位置进行拆分时,split函数才会创建一个空字符串.字符串对象.
谢谢马丁...
Yes Only the split function creates an empty string when the splitting is done at the last position of the string object.
Thank You Martin...


这篇关于为什么总是在结尾处将空字符串[非空白]添加到字符串变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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