Click here to Skip to main content
15,902,299 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to increase the string value for each loop. Is it possible to increase the static string?

I know I can get the answer that I want if I put the variable inside for loop. But in this program, I want to try with static variable so that it can shares the value of it among all instances of the class.

Output that I get currently:
1
number: //10.0.0.1
2
number: //10.0.0.1
3
number: //10.0.0.1

What I have tried:

private static string number = @"//10.0.0.ZZ";


for (int i = 1; i < 4; i += 1)
     {

         number = number.Replace("ZZ", $"{i.ToString()}");
         Console.WriteLine(i);
         Console.WriteLine("number: " + number));

     }
Posted
Updated 25-Apr-22 23:18pm

Why are you using Replace? All you need is:
C#
string number = @"//10.0.0.";
for (int i = 1; i < 4; i += 1)
{
    Console.WriteLine($"{number}{i}");
}
 
Share this answer
 
Comments
CPallini 26-Apr-22 6:18am    
Indeed.
That's the best solution.
5.
Richard MacCutchan 26-Apr-22 6:22am    
Thanks. Rather obvious given he is already using the $-style format control.
Remember that strings are immutable - once created they cannot actually be changed. Every time you try to change a string, what you actually do is create a new string.

So if you use number as a template instead of replacing it each time:
C#
private static string number = @"//10.0.0.ZZ";

for (int i = 1; i < 4; i += 1)
     {
         string IP = number.Replace("ZZ", $"{i.ToString()}");
         Console.WriteLine(i);
         Console.WriteLine("number: " + IP));
     }
Or better
C#
private const string number = @"//10.0.0.ZZ";

for (int i = 1; i < 4; i++)
     {
         string IP = number.Replace("ZZ", i.ToString());
         Console.WriteLine(i);
         Console.WriteLine($"Number: {IP}");
     }
 
Share this answer
 
v2
It would work, but your code is wrong:
  • The very first time ZZ is replaced by 1 (so far so good).
  • Then (in the successive iterations) you have no more ZZ in your string and no replacement happens.
You should replace anything on the right side of the last dot, with the proper number.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900