[英]How to read characters of string or character array without using length function
I want to read all the characters from the string without using the built in functions.I tried the below. 我想从字符串中读取所有字符而不使用内置函数。我尝试了以下方法。
char[] str ={ 'k','r','i','s'};
for ( int i = 0; str[i]!='\0'; i++)
{
Console.WriteLine(str[i]);
}
But I get an exception because unlike in c I don't see the string here ends with a null character. 但是我得到一个例外,因为与c不同,我看不到这里的字符串以空字符结尾。 Is there any other way (apart from using built functions/try catch block in case of exception) I can read all the characters of the string ? 还有其他方法(除了在异常情况下使用内置函数/ try catch块之外),我可以读取字符串的所有字符吗?
In c# arrays have Length
property: 在c#中,数组具有Length
属性:
char[] str ={ 'k','r','i','s'};
for (int i = 0; i < str.Length; i++)
{
Console.WriteLine(str[i]);
}
Otherwise you can use foreach
which will enumerate all characters in an array. 否则,您可以使用foreach
来枚举数组中的所有字符。
If what you really want is to display the string that the characters in the char array produce: 如果您真正想要显示的是char数组中的字符产生的字符串:
char[] mychars = { 'k', 'r', 'i', 's' };
Console.WriteLine("Your characters form the following string: " + new string(mychars));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.