Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Tom Coomer
1,331 PointsChanging Text from array
I would like to change a string to the value of an array. E.g. String = @"Hello"
Array 1 = [@"Hello",@"Goodbye"] Array 2 = [@"Howdy",@"Night night"]
String = replace @"Hello" with @"Howdy"
Thanks for your help. I have been stuck on this for a while.
Tom Coomer
1,331 PointsIf the string value is equal to one of the objects in the arrtay I would like to change the string value to its corresponding value in the second array. If the string value is object 5 in array 1 then replaces with object 5 in array 2.
2 Answers
Wilhelm Michaelsen
449 Pointsfor (int i = 0; i < [yourArray count]; i++) {
if (yourString == yourArray[i] {
yourString = yourSecondArray[i];
}
}
This loops through the first array and checks if the string equals something in the first array. If it does match some index it is set to the same index in the second array. This should solve your problem. Tell me if it doesn't!
Tom Coomer
1,331 Pointsthe if statement does not seem to be detecting the string match. Should the array value of "yourArray" be converted into a string?
Wilhelm Michaelsen
449 Pointssorry I only put one = in the if statement, it should be == (2x). If all your elements in your array are strings you should not have to convert them to a string if they already are.
Tom Coomer
1,331 PointsThat is working now. Thanks I have just changed it so the string is the value of a textfield (textfield.text) and it is not recognising it. Do you know why this would be? Below is the code.
myString = myTextField.text;
for (int i = 0; i < [array1 count]; i++) {
if (myString == array1[i]) {
myString = array2[i];
}
}
NSLog(myString);
Wilhelm Michaelsen
449 PointsIs the problem that it doesn't recognize the textfields value?
Tom Coomer
1,331 PointsIt recognises it if I write:
NSLog(myString);
But not if I use it as the string to compare.
Wilhelm Michaelsen
449 PointsIf you NSLOG(myString); inside the if statement before the mystring = array2[i]; what does it log?
Tom Coomer
1,331 PointsIt does not log anything.
Wilhelm Michaelsen
449 PointsWilhelm Michaelsen
449 PointsI dont understand your question, do you want to assign an array value to a new string variable? Or do you want to change an array value to a value of another array?