在 C# 中使用 string.Remove('\n') 在一处截断字符串
Using string.Remove('\n') in C# truncates the string at one point
我有一串带换行符的IP地址。
我需要从文字中删除所有换行符。所以我用了 string.Remove()
现在,一旦调试器越过这条线,表达式的结果就会截断为“192.168.20”
为什么会这样。我不想使用替换,我想去掉 '\n'
String.Remove 不带字符而是带索引。
\n
整数形式是 10
这样就解释了你的行为。
你要找的是这样的东西:
result = input.Replace("\n", "");
如果您查看 documentation,您会发现实际上并没有需要删除字符的 string.Remove
重载。
我希望 char
被隐式转换为 int
而你正在点击 string.Remove(startIndex)
:
Returns a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted.
\n
会转换为字符的十进制值 10,因此会作为位置 10 传递给 string.Remove
,因此之后的所有内容都会被删除,这就是我们看到的情况:192.168。 20 是 10 个字符长。
如果您只想删除第一个 \n
之后的所有内容(包括第一个 \n
),我建议您这样做:
int idx = input.IndexOf("\n", StringComparison.InvariantCulture);
if (idx != -1)
{
input = input.Remove(idx);
}
或者简单地替换 \n
的所有实例,使用 replace
(我知道你说过你不想这样做,但以防万一):
input = input.Replace("\n", string.Empty, StringComparison.InvariantCulture);
我有一串带换行符的IP地址。 我需要从文字中删除所有换行符。所以我用了 string.Remove()
现在,一旦调试器越过这条线,表达式的结果就会截断为“192.168.20”
为什么会这样。我不想使用替换,我想去掉 '\n'
String.Remove 不带字符而是带索引。
\n
整数形式是 10
这样就解释了你的行为。
你要找的是这样的东西:
result = input.Replace("\n", "");
如果您查看 documentation,您会发现实际上并没有需要删除字符的 string.Remove
重载。
我希望 char
被隐式转换为 int
而你正在点击 string.Remove(startIndex)
:
Returns a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted.
\n
会转换为字符的十进制值 10,因此会作为位置 10 传递给 string.Remove
,因此之后的所有内容都会被删除,这就是我们看到的情况:192.168。 20 是 10 个字符长。
如果您只想删除第一个 \n
之后的所有内容(包括第一个 \n
),我建议您这样做:
int idx = input.IndexOf("\n", StringComparison.InvariantCulture);
if (idx != -1)
{
input = input.Remove(idx);
}
或者简单地替换 \n
的所有实例,使用 replace
(我知道你说过你不想这样做,但以防万一):
input = input.Replace("\n", string.Empty, StringComparison.InvariantCulture);