Add incremented number to string - c#

I want to add a number to the end of a string.
eg.
john1
beth2
mike3
mary4
class finalName
{
public string name(string initialName)
{
string finalName = string.Empty;
for (int i = 1; i < 10; i++)
{
finalName = initialName + i.ToString("0");
}
return finalName;
}
}
finalName name = new finalName();
The result that I am getting is:
jonh9
beth9
mike9
mary9
What am I doing wrong?

What you want to do is modify your method so it takes a collection of names, then modifies those with an incrementing indexer:
public static IEnumerable<string> ModifyNames(IEnumerable<string> names)
{
int index = 1;
foreach (string name in names)
{
yield return name + index;
index++;
}
}
Fiddle here

You are just looping inside the method and returns the last value.
If you want each call of the function to add an incremented number, then add this counter as a field in your class and add it to the string:
int counter = 1;
public string name(string initialName)
{
return initialName + counter++;
}
If you are creating a new instance every call, then the variable should be made static:
static int counter = 1;
public string name(string initialName)
{
return initialName + counter++;
}
If you would like to send in a list of strings to the function and get back the list with an incremented number then you should first change the signature to get a collection and return a collection:
public IEnumerable<string> name(IEnumerable<string> names)
{
return names.Select( (s,i) => s+(i+1));
}

You should remove for loop from your name function.
Your loop always ends with i equal to 9 and result is always initialName + 9.
I think that you need something like this:
string[] names = new string[] { "john", "beth", "mike", "mary" };
for (int i = 0; i < names.Length; i++)
{
names[i] = names[i] + (i + 1).ToString();
}

Related

Finding odd or even in an C# array

I'm supposed to create a method that takes an array and tells if the number is odd or even. I think I'm close to the answer but when I ran the code, it popped up with "Index is outside the bounds of the array". Is there a way to fix that?
private static string OddOrEven(int[] integerArray, string[] numAssign)
{
foreach (int i in integerArray)
{
if (integerArray[i] % 2==0)
{
numAssign[i] = " is even";
string returnValue = integerArray[i] + numAssign[i];
return returnValue;
}
else
{
numAssign[i] = " is odd";
string returnValue = integerArray[i] + numAssign[i];
return returnValue;
}
}
return "";
}
I'm still new to c# so any help is really appreciated.
Your mistake here is with how foreach works. I'll provide a different example to help you understand:
List<Person> people = GetPeople();
foreach (Person p in people)
{
Console.WriteLine(p.Name);
}
As you can see, the variable in the foreach actually receives each item, not its index. It's just that you have a list of int so it's not so obvious for you.
It seems like you want a regular for loop:
for(int i = 0; i < integerArray.Length; ++i)
{
if (integerArray[i] % 2==0)
{
numAssign[i] = " is even";
string returnValue = integerArray[i] + numAssign[i];
return returnValue;
}
else
{
numAssign[i] = " is odd";
string returnValue = integerArray[i] + numAssign[i];
return returnValue;
}
}
The next curious thing is your return returnValue; - the if statement can only ever enter one or the other, so it will always return a string for the first item only. It won't go on to the second, third, fourth, etc. item as it has already left the method before the loop has a chance to move on to the next value.
Speculation
I expect you want an array of results like this:
private static string[] OddOrEven(int[] integerArray)
{
string[] resultValues = new string[integerArray.Length];
for (int i = 0; i < integerArray.Length; ++i)
{
if (integerArray[i] % 2==0)
{
string numAssign = " is even";
resultValues[i] = integerArray[i] + numAssign;
}
else
{
string numAssign = " is odd";
resultValues[i] = integerArray[i] + numAssign;
}
}
return resultValues;
}
Note that I've removed the numAssign incoming array from the method parameters, and now just build it within the method itself.
This would produce a result like this.

Changing the index of arrays

I am stuck at this the following problem. I am trying to create an array with pre-specified size and elements. Later I ask the user to provide me a name they want to add. I then create a new array of one size bigger and add the name new on the last place. Later I ask the user to provide me with a name from the array they wish to remove. And that's where the problem arises. I know I can use the method Array-Copy etc. but I want this to be solved only through index. Here is the code I have written so far:
class Program
{
static void Main(string[] args)
{
string[] names = { "Adam", "Eva" };
foreach (var item in names)
{
Console.WriteLine(item);
}
Console.Write("Skriv in ett namn du vill lägga till: ");
string newAdd = Console.ReadLine();
string[] addedNames = AddName(names, newAdd);
foreach (var item in addedNames)
{
Console.WriteLine(item);
}
Console.Write("Ange det element du vill ta bort: ");
string tabort = Console.ReadLine();
string[] removedNames = RemoveName(addedNames, tabort);
foreach (var item in removedNames)
{
Console.WriteLine(item);
}
}
static string[] AddName(string[] names, string newAdd)
{
string[] newNames = new string[names.Length + 1];
for (int i = 0; i < names.Length; i++)
{
newNames[i] = names[i];
}
newNames[newNames.Length - 1] = newAdd;
return newNames;
}
static string[] RemoveName(string[] addedNames, string tabort)
{
string lLName = tabort.ToLower();
string[] newnames = new string[addedNames.Length - 1];
if (lLName == addedNames[0].ToLower())
{
int index = 0;
for (int i = 1; i < addedNames.Length; i++)
{
newnames[index] = addedNames[i];
index++;
}
}
else if (lLName == addedNames[addedNames.Length-1].ToLower())
{
for (int i = 0; i < addedNames.Length-1; i++)
{
newnames[i] = addedNames[i];
}
}
else if (lLName != addedNames[addedNames.Length-1].ToLower() && lLName != addedNames[0].ToLower())
{
for (int i = 1; i < addedNames.Length; i++)
{
}
}
return newnames;
}
}
}
So you can see that I am trying to implement the last else if statement, but I am not sure how to deal when the name provided by the user appears somewhere in my addedNames array except on the first and last places.
I would also love if you think there is an easier way to deal with the problem instead haveing almost 4 if statements for each case. It seems for me that if one manages to implement the last if statement then it will work regardless where the name, provided by the user to be removed, iss located in the addedNames array.
Why not just find the index of the name that needs to be replaced (tabort), and just change the value to newAdd?
string newAdd = Console.ReadLine();
string tabort = Console.ReadLine();
int i = Array.FindIndex(names, x => x.Contains(tabort));
names[i] = newAdd;

How to efficiently declare objects [duplicate]

I was wondering whether there's a way in a "for" loop to assign a value to a string variable named according to its index number?
let's say I have 3 string variables called:
string message1 = null;
string message2 = null;
string message3 = null;
And I want the 'for' loop to do the something like the following code:
for (int i = 1; i <=3; i++)
{
messagei = "blabla" + i.ToString();
}
I don't want to use an "if" or a "switch" because it will make the code harder to follow.
Is there a way to do that?
You don't want 3 variables with the same name, you want an array of those variables.
string[] messages = new string[3]; // 3 item array
You can then store your items in the array elements
messages[0] = "Apple"; // array index starts at 0!
messages[1] = "Banana";
messages[2] = "Cherry";
Another way to create that array is an inline array initializer, saves some code
string[] messages = { "Apple", "Banana", "Cherry" };
(Note: there are more valid syntaxes for array initialization. Research on the various other methods is left as an exercise.)
And access them via a loop (foreach)
foreach (string fruit in messages)
{
Console.WriteLine("I'm eating a " + fruit);
}
Or for
for (int i = 0; i < messages.Length; i++)
{
Console.WriteLine("I'm eating a " + messages[i]); // reading the value
messages[i] = "blabla" + i.ToString(); // writing a value to the array
}
can you use an array? or list type?
string[] messages = new string[3];
for (int i = 1; i <=3; i++)
{
messages[i] = "blabla" + i.ToString();
}
You said you don't want to have a switch statement. I realize this does have a switch, but if you must have three different variables, you could encapsulate your switch inside a function call:
string message1 = null;
string message2 = null;
string message3 = null;
void SetMessage(int i, string value)
{
if(i == 1)
message1 = value;
etc
}
for (int i = 1; i <=3; i++)
{
SetMessage(i, "blabla" + i.ToString());
}
Not an optimal solution but if you MUST have separate variables it will hide the mess.
You can't do that (well, not sanely). Have you considered using an array of strings instead?
I think you should use an array for this kind of variables.
string[] message = new string[3];
for (int i = 1; i <=3; i++)
{
message[i] = "blabla" + i.ToString();
}
Usually instead of having N differents variables named 1, 2, ..., N the way is to store them in an array:
string message[3];
message[0] = null;
message[1] = null;
message[2] = null;
and then the loop:
for (int i = 0; i <=2; i++)
{
message[i] = "blabla" + i.ToString();
}
Note that, usually again, a set of indexed variables starts with value 0 ;)
I would go about it a little differently, maybe use a dictionary and store your messages. Something like this:
Dictionary<string, string> messages = new Dictionary<string, string>();
for(int i = 1; i <= 3; i++)
{
messages.Add("message" + i.ToString(), i.ToString());
}
You can also do it without the index:
string[] Messages = { "Tom", "Dick", "Harry" };
foreach (String Message in Messages)
{
Response.Write("Hello " + Message + "<br />");
}
If you declare your variable in a class as public variables, you can access them as follow;
public partial class _Default : System.Web.UI.Page
{
public string message1 = null;
public string message2 = null;
public string message3 = null;
public void setVars()
{
for (int i = 1; i <=3; i++)
{
this.GetType().GetField("message" + i.ToString()).SetValue(this, "blabla" + i.ToString());
}
}
}

C# Variable not getting all values outside for loop

I have two values in the dictionary but when I try to get the two values outside the loop I am only getting one value. The locationdesc variable value are being overwritten. Is there a better way to create unique variables to handle this issues
There are two keys location-1 and location-2. I am trying to figure out how to get both the values outside the loop. Am I doing it wrong?
string locationDesc = "";
string locationAddress = "";
int count = dictionary.Count(D => D.Key.StartsWith("location-"));
for (int i = 1; i <= count; i++)
{
if (dictionary.ContainsKey("location-"+i))
{
string locationData = dictionary["location-"+i];
string[] locationDataRow = locationData.Split(':');
locationDesc = locationDataRow[0];
locationAddress = locationDataRow[1];
}
}
// Only getting location-2 value outside this loop since locationDesc is not unique.
Debug.WriteLine("Location Desc from dictionary is : " + locationDesc);
Debug.WriteLine("Location Add from dictionary is : " + locationAddress);
What I would like to get here is get both the values like locationDesc1 and locationDesc2 instead of locationDesc
What I am looking for is to create locationDesc and locationAddress unique so I can access both the values outside the for loop.
More Explanation as I was not very clear:
I have a dynamic table that will be created in the front end. Every time a location is created I create a cookie. For e.g. location-1, location-2 ...location-n with the location description and location values as values in the cookie. I am trying to access these values in the backend by creating a dictionary so I can assign all the values to unique variable which will make it easier for me to pass these values to a api call. I think I am over complicating a simple issue and might be doing it wrong.
My api call will be something like this:
<field="" path="" value=locationDesc1>
<field="" path="" value=locationDesc2>
The problem with your loop is that you are relying on the position of the entry in the dictionary matching the index within your loop. Your first line of code pretty much has it though:
int count = dictionary.Count(D => D.Key.StartsWith("location-"));
What this tells me is that you are looking for all entries in your dictionary where the key starts with "location-". So why not do that directly:
var values = dictionary.Where(d => d.Key.StartsWith("location-"));
And to do the extraction/string splitting at the same time:
var values = dictionary
.Where(d => d.Key.StartsWith("location-"))
.Select(d => d.Item.Split(':')
.Select(s => new
{
LocationDesc = s[0],
LocationAddress = s[1]
});
This will give you an IEnumerable of LocationDesc/LocationAddress pairs which you can loop over:
foreach(var pair in values)
{
Debug.WriteLine(pair.LocationDesc);
Debug.WriteLine(pair.LocationAddress);
}
Try this:
int count = dictionary.Count(D => D.Key.StartsWith("location-"));
Dictionary<string, string> values = new Dictionary<string, string>();
for (int i = 1; i <= count; i++)
{
if (dictionary.ContainsKey("location-"+i))
{
string locationData = dictionary["location-"+i];
string[] locationDataRow = locationData.Split(':');
values.Add(locationDataRow[0],locationDataRow[1]);
}
}
foreach (var item in values)
{
Debug.WriteLine(item.Key + " : " + item.Value);
}
As you are dealing with multiple values, you should go with a container where you can store all the values.
if you are dealing with only two unique values then use below code.
int count = dictionary.Count(D => D.Key.StartsWith("location-"));
string[] locationDesc = new string[2];
string[] locationAddress = new string[2];
for (int i = 1; i <= count; i++)
{
if (dictionary.ContainsKey("location-"+i))
{
string locationData = dictionary["location-"+i];
string[] locationDataRow = locationData.Split(':');
locationDesc[i-1] = locationDataRow[0];
locationAddress[i-1] = locationDataRow[1];
}
}
for (int i = 0; i <= locationDesc.Length-1; i++)
{
Debug.WriteLine("Location Desc from dictionary is : " + locationDesc[i]);
Debug.WriteLine("Location Add from dictionary is : " + locationAddress[i]);
}
if number of unique values is not fixed then go with ArrayList
int count = dictionary.Count(D => D.Key.StartsWith("location-"));
ArrayList locationDesc = new ArrayList();
ArrayList locationAddress = new ArrayList();
for (int i = 1; i <= count; i++)
{
if (dictionary.ContainsKey("location-"+i))
{
string locationData = dictionary["location-"+i];
string[] locationDataRow = locationData.Split(':');
locationDesc.Add(locationDataRow[0]);
locationAddress.Add(locationDataRow[1]);
}
}
for (int i = 0; i < locationDesc.Count; i++)
{
Debug.WriteLine("Location Desc from dictionary is : " + locationDesc[i]);
Debug.WriteLine("Location Add from dictionary is : " + locationAddress[i]);
}
Simple One. If you only want to show result using Debug.WriteLine, then go with below code
int count = dictionary.Count(D => D.Key.StartsWith("location-"));
for (int i = 1; i <= count; i++)
{
if (dictionary.ContainsKey("location-"+i))
{
string locationData = dictionary["location-"+i];
string[] locationDataRow = locationData.Split(':');
Debug.WriteLine("Location Desc from dictionary is : " + locationDataRow[0]);
Debug.WriteLine("Location Add from dictionary is : " + locationDataRow[1]);
}
}
Not able to prepare Code in Visual Studio at the moment therefore there may be some syntax errors.
It is hard to judge what you are event trying to do. I would not just be dumping objects you already have into other objects for fun. If you are just trying to expose values in a loop for use with another function, you can just use LINQ to iterate over the dictionary. If you want a specific value just add a where LINQ expression. LINQ should be in any .NET framework after 3.5 I believe.
public static void ApiMock(string s)
{
Console.WriteLine($"I worked on {s}!");
}
static void Main(string[] args)
{
var d = new Dictionary<int, string> {
{ 1, "location-1" },
{ 2, "location-2" },
{ 3, "location-3" }
};
d.ToList().ForEach(x => ApiMock(x.Value));
//I just want the second one
d.Where(x => x.Value.Contains("-2")).ToList().ForEach(x => ApiMock(x.Value));
//Do you want a concatenated string
var holder = string.Empty;
d.ToList().ForEach(x => holder += x.Value + ", ");
holder = holder.Substring(0, holder.Length - 2);
Console.WriteLine(holder);
}

increasing names in C# with integers

I need to get an object and check if it already exists.
In case it does, I want to add a number, or increase the number in its name.
For example if I have the object "a" and it exists, I need to add a 1 so it's called a1.
In case a1 exists, a2, etc.
How could I perform this?
My code:
if (e.TreeNode.Tag is Variant)
{
if (variantExists(e.TreeNode.Text))
{
Random r = new Random();
int randomNumber = r.Next(0, 99);
e.TreeNode.Text = e.TreeNode.Text + randomNumber;
//e.TreeNode.Remove();
return;
}
}
Can you change the TreeNode class? I would add properties for Label (Name without Index) and Index and make the Name property read only, i.e
class TreeNode
{
public int Index {get;set;}
public string Label {get;set;}
public string Name
{
get { return Index == 0 ? Label : Label + Index; }
}
}
In your code you just need to set the Index property to the value you need and dont worry about the whole string parsing stuff
string name = "SomeName";
string tempName = name;
int n = 0;
while (DoesNameExist(tempName))
{
n++;
tempName = name + n;
}
name = tempName;
This gets ineffecient for large numbers of the same object, but that shouldn't happen right?
The problem with doing it the other way around, and stripping off trailing numbers to find the "original" name is that the original name may genuinely have numbers on it.
Eg. You say you add:
SomeName
SomeName99
SomeName
SomeName99
The above code will give you
SomeName
SomeName1
SomeName99
SomeName991
Something along the lines of this could work:
var existingItems = new HashSet<string>();
var items = new List<string>{"a", "b", "a"};
foreach (var item in items)
{
var tempItem = item;
var i = 1;
while (!existingItems.Add(tempItem))
tempItem = tempItem + i++;
}

Categories

Resources