简体   繁体   English

递归中未修改字符串值

[英]String value not getting modified in a recursion

I am trying to modify a string inside a recursion.我正在尝试修改递归中的字符串。 Here is the code:-这是代码: -

using System;


public class Program
{
    public static void Main()
    {
        string s = "abcdc";
        string added = "";
        checkIfPalindrome(s , added);
        Console.WriteLine( added);
    }

    public static void checkIfPalindrome(string s ,  string added)
    {
        //Console.WriteLine(added);
        if(s.Length < 2)
        {
            return;
        }
        if(s[0] == s[s.Length -1])
        {           
            checkIfPalindrome(s.Substring(1,s.Length-2) , added);       
        }
        else
        {           
            added = s[0] + added;           
            checkIfPalindrome(s.Substring(1,s.Length-1), added) ;
        }

    }
}

Here is the fiddle for the same:-这是相同的小提琴:-

 <iframe width="100%" height="475" src="https://dotnetfiddle.net/Widget/u4119h" frameborder="0"></iframe>

I am expecting added to be modified inside recursion and appear as a result outside function call and inside main method, since string is a reference type.But the value of added literal is an empty string.我期望添加在递归内部进行修改,并作为结果出现在 function 调用和 main 方法内部,因为字符串是引用类型。但是added的文字的值是一个空字符串。 Although when recursion hits the base case, it has ba as value.虽然当递归遇到基本情况时,它的值是ba

Also correct value is reflected when ref keyword is used for passing addedref关键字用于传递added时,也会反映正确的值

Is my understanding wrong?我的理解错了吗?

At the very top, you're assigning a value to the added local in your Main function.在最顶部,您正在为Main function 中added的本地分配一个值。 But you're never changing that value.但是你永远不会改变那个值。 You're only ever changing what the argument of checkIfPalindrome points to.你只会改变checkIfPalindrome的论点所指向的内容。 This has no effect on the local added in Main , unless you pass it by reference - using ref .这对Mainadded的本地没有影响,除非您通过引用传递它 - 使用ref

Reference types have reference semantics, yes.引用类型具有引用语义,是的。 But that doesn't mean that a reference to a reference type has the same property.但这并不意味着对引用类型的引用具有相同的属性。 If you modified the value of added , you would get the behaviour you expect - but you only ever replace the argument's reference - pointing it somewhere else.如果你修改了added的值,你会得到你期望的行为——但你只会替换参数的引用——将它指向其他地方。 Of course, strings in .NET are immutable, so you can't actually change the value of added - your only option is to pass the string by reference (or better, make it a return value, which makes for much clearer recursion anyway).当然,.NET 中的字符串是不可变的,因此您实际上无法更改added- 您唯一的选择是通过引用传递字符串(或者更好的是,将其设为返回值,这使得递归更加清晰)。

string is a reference type but immutable which means it cannot be changed after it has been created. string是一种reference type ,但immutable ,这意味着它在创建后无法更改。 Every change to a string will create a new string.对字符串的每次更改都会创建一个新字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM