Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 混淆字符串。删除_C#_.net_String - Fatal编程技术网

C# 混淆字符串。删除

C# 混淆字符串。删除,c#,.net,string,C#,.net,String,我在理解为什么String.Remove在我的特定场景中不起作用时遇到了一些问题。我有一种方法(仅用于一些实践),它根据给定位置删除字符串中的字符,并按如下方式工作: public static string RemoveCharacter(string word, int pos_to_del) { int string_length = word.Length; if (Enumerable.Range(0, string_l

我在理解为什么String.Remove在我的特定场景中不起作用时遇到了一些问题。我有一种方法(仅用于一些实践),它根据给定位置删除字符串中的字符,并按如下方式工作:

public static string RemoveCharacter(string word, int pos_to_del)
        {
            int string_length = word.Length;

            if (Enumerable.Range(0, string_length - 1).Contains(pos_to_del))
            {
                word = word.Remove(pos_to_del, pos_to_del);
            }
            return word;
        }
如果pos_to_del>0,它将工作(例如word=hello和pos_to_del=1,result=hllo)。但是,如果用户希望位置为第一个字符(0),则此操作将不起作用。我不知道我是否已经直接编写了太长时间的代码,并且犯了一个简单的错误,或者我是否真的误解了其中的任何一点

第二个参数是
要删除的字符数。
。您需要:

word = word.Remove(pos_to_del, 1);

首先,这句话不好:

if (Enumerable.Range(0, string_length - 1).Contains(pos_to_del))
这句话不是你的问题的原因,但它是一个问题。如果字符串很长,则生成的数字序列与该字符串一样长。这可能非常低效,而且没有必要。您只需使用一个简单的比较:

if (pos_to_del >= 0 && pos_to_del < word.Length)
仅供参考
如果(pos-to-del=0)
将更有意义。
word = word.Remove(pos_to_del, 1);