I need to replace characters in an array using ONLY a loop. I can't do anything more advanced than that. What should I do?

c program to replace a character in a string using recursion
replace character recursively c++
c replace character in string at position
c++ replace character in char array
c replace multiple characters in string
c string replace character
c program to replace a string with another string
replace character in string c++

I'm working on a faux DNA strand analyzer, and I need to create the complement strand to this one:

char [] testStrand = {'A', 'T', 'T', 'A', 'G', 'C', 'T', 'A', 'T', 'G', 'A', 'A', 'C', 'C', 'T', 'A', 'C', 'C', 'A', 'T'};

Note: These are 20 characters, if that helps.

I can't hardcode this, and I need to use a loop to iterate through each character and find out how to swap the A's with T's (and vice versa) and the G's with C's (and vice versa.)

The simplest solution:

char[] testStrand = {'A', 'T', 'T', 'A', 'G', 'C', 'T', 'A', 'T', 'G', 'A', 'A', 'C', 'C', 'T', 'A', 'C', 'C', 'A', 'T'};
char[] newTestStrand = new char[testStrand.length];
for (int i = 0, l = testStrand.length; i < l; i++)
{
   if (testStrand[i] == 'A')
   {
      newTestStrand[i] = 'T';
   }
   else if (testStrand[i] == 'T')
   {
      newTestStrand[i] = 'A';
   }
   else if (testStrand[i] == 'C')
   {
      newTestStrand[i] = 'G';
   }
   else if (testStrand[i] == 'G')
   {
      newTestStrand[i] = 'C';
   }
   else
   {
      newTestStrand[i] = testStrand[i];
   }
}

or with switch statement (not sure if you're allowed to use that):

char[] testStrand = {'A', 'T', 'T', 'A', 'G', 'C', 'T', 'A', 'T', 'G', 'A', 'A', 'C', 'C', 'T', 'A', 'C', 'C', 'A', 'T'};
char[] newTestStrand = new char[testStrand.length];
for (int i = 0, l = testStrand.length; i < l; i++)
{
   switch (testStrand[i])
   {
      case 'A':
        newTestStrand[i] = 'T';
        break;
      case 'T':
        newTestStrand[i] = 'A';
        break;
      case 'G':
        newTestStrand[i] = 'C';
        break;
      case 'C':
        newTestStrand[i] = 'G';
        break;
      default:
        newTestStrand[i] = testStrand[i];
        break;
    }
}

But in reality I'd recommend representing the swaps somehow (key value pairs) and looping through the potential swaps. I stuck to the simple solution since you said "loops only"

Replace a character c1 with c2 and c2 with c1 in a string S , If c1 is found then replace it with c2 and else if c2 is found replace it with c1. loop to traverse in the string Replace all occurrences of a string with space · Convert the string into palindrome string by changing only one character. If you like GeeksforGeeks and would like to contribute, you can also write an article using  this would change the second character of the string at pFeilds[1] to a n, again assuming the string in more then 2 characters long. so with this information, all we have to do is loop over each character in the array checking if its the token you want to replace, and if it is replace it, until we find a null(0) then stop.

Since somebody already suggested the else/if approach, here's the same but with ternary operators instead:

char[] testStrand = {'A', 'T', 'T', 'A', 'G', 'C', 'T', 'A', 'T', 'G', 'A', 'A', 'C', 'C', 'T', 'A', 'C', 'C', 'A', 'T'};
for (int i = 0; i < testStrand.length; i++) {
    testStrand[i] = testStrand[i] == 'A' ? 'T' :
        testStrand[i] == 'T' ? 'A' :
            testStrand[i] == 'G' ? 'C' :
                testStrand[i] == 'C' ? 'G' : testStrand[i];
}
Update

I noticed you asked how to insert the new values in a different array:

char[] testStrand = {'A', 'T', 'T', 'A', 'G', 'C', 'T', 'A', 'T', 'G', 'A', 'A', 'C', 'C', 'T', 'A', 'C', 'C', 'A', 'T'};
char[] reversed = new char[testStrand.length];

for (int i = 0; i < testStrand.length; i++) {
    if (testStrand[i] == 'A') {
        reversed[i] = 'T';
    } else if (testStrand[i] == 'T') {
        reversed[i] = 'A';
    } else if (testStrand[i] == 'C') {
        reversed[i] = 'G';
    } else if (testStrand[i] == 'G') {
        reversed[i] = 'C';
    } else {
        reversed[i] = testStrand[i];
    }
}
Update 2

But hey, if you're feeling wild:

Character[] testStrand = {'A', 'T', 'T', 'A', 'G', 'C', 'T', 'A', 'T', 'G', 'A', 'A', 'C', 'C', 'T', 'A', 'C', 'C', 'A', 'T'};
List<Character> chars = Arrays.asList(testStrand);
chars.replaceAll(c -> {
    switch (c) {
        case 'A': return 'T';
        case 'T': return 'A';
        case 'C': return 'G';
        case 'G': return 'C';
        default: return c;
    }
});

// print them out
chars.forEach(System.out::println);

C Program to Replace All Occurrence of a Character in a String, This program allows the user to enter a string (or character array), and a character value. Next, it will search and replace all occurrences of a character inside a string. printf("\n Please Enter any String : "); gets(str); printf("\n Please Enter the Character that you want to Here, we just replaced the For Lop with While Loop. As we have passed the count parameter as 2, so only first 2 occurrences of ‘s’ will be replaced in the returned copy. Replace multiple characters/strings in a string. str.replace() function can replace the occurrences of one given sub string only. But what if we want to replace multiple sub strings in a given string ? Suppose we have a

Jimmyv code: Better?

char[] complementstrand = {'A', 'T', 'T', 'A', 'G', 'C', 'T', 'A', 'T', 'G', 'A', 'A', 'C', 'C', 'T', 'A', 'C', 'C', 'A', 'T'};
    for (int i = 0; i < complementstrand.length; i++) {

    if (Character.toString(complementstrand[i]).equals("A")){
complementstrand[i] = "T".charAt(0);
}

    else if (Character.toString(complementstrand[i]).equals("T")){
complementstrand[i] = "A".charAt(0);
}


    else if (Character.toString(complementstrand[i]).equals("G")){
complementstrand[i] = "C".charAt(0);
}


    else if (Character.toString(complementstrand[i]).equals("C")){
complementstrand[i] = "G".charAt(0);
}


}
System.out.println(Arrays.toString(complementstrand));

Best way to change a certain char in an array in C++. Easy one for , However, since you are using character arrays, you might want to but the suggestion of calling "strchr()" multiple times to do this kind of replace the for loop a few posts above), then it will run just a hair faster than the char  For-Each Loop is another form of for loop used to traverse the array. for-each loop reduces the code significantly and there is no use of the index or rather the counter in the loop. Syntax: For(<DataType of array/List><Temp variable name> : <Array/List to be iterated>){ System.out.println(); //Any other operation can be done with this temp variable.

C++ Primer Plus: C++ Primer Plus _p6, This function could (but doesn't need to) use the first version internally. For example, a loop should solicit input for an array of golf structures and terminate when the array is full or the user replacing the character array with a string object. Substring to replace, specified as a string array, character vector, or cell array of character vectors. Data Types: string | char | cell

PHP and MySQL Web Development, $filearray = file ($fp); This will read the entire file into the array called $filearray. It takes a file pointer as its only parameter and returns the next character in the file. We can replace the while loop in our original script with one that uses fgetc We need to test feof () again after we've read the character because we don't  The Replace function in Excel VBA is an inbuilt function or a pre-defined function, which you can use in your Macro to replace a set of characters in a string with another set of characters. You can replace characters in a given string or replace characters in a cell or a specified range in your Excel worksheet.

Ivor Horton's Beginning Visual C++ 2005, using std::cout; using std::endl; int main() { const int MAX = 80; // Maximum array dimension char buffer[MAX]; // Input buffer int count = 0; // Character count the keyboard ends when the user presses Return, or when MAX-1 characters have been read. By using the strlen() function you could replace the while loop with the  Every string literal (something in double-quotes) implicitly contains the null character at the end Since character arrays are used to store C-style strings, you can initialize a character array with a string literal (i.e. a string in double quotes), as long as you leave room for the null character in the allocated space.

Comments
  • You should write some code. Did you try anything?
  • By the way, I realize that other questions were answered like this, but I need a more specific answer.
  • I'm guessing you need computer script, not pencil eraser...., What language would you like me to show you?
  • @EJoshuaS No, because I don't even know where to begin. Should I make an array of complements?
  • @Alex you can't do it only with a loop. At the very least, you need something to map the letters to their complement.
  • Thank you! This is within what we've learned so far, and it is EXACTLY what I needed. One last question: how might I put these in a new array without hardcoding it all? Should I just put them in as testStrand[x], where x is whatever number I need?
  • Wait, no, forget that. How can I make the new array? I just realized what I said was stupid, and wouldn't work.
  • I edited my answer above to do just that. You'll notice I declared a new array of the same length (line 2). Then I set each element of the new array to the same element of the old array (unless it needed to be replaced).
  • ...or switch statements are cleaner
  • Agreed that switch statements are much cleaner, but I thought maybe that would surpass the "for loop only" requirement :)
  • always love ternary, but maybe too advanced for this cat
  • yeh, i guess we should always try to give good examples of best-practice code. Anyone want to throw out a try-catch-finally?