Replacement of random string/char array characters using match ups
while (1)
{
char j;
if (x[j] == y[j])
Here I am trying to start a loop where I want to able to match any of the characters from char array 'x' with char array 'y'. If the characters do match from x to y then I want to keep them as they are and if they don't I want to be able to replace them with a star '*'. (e.i. x = [a,p,f]
and y = [a,p,p,l,e]
and so after the match up and replacement y = [a,p,p,*,*]
and when I cout
开发者_JS百科it spells out app**
)
I have no idea how to set this up and what type of loop I should use. I fairly new to programming and I know basic replace and switch functions.
This more or less does what you specify, I think.
#include <string.h>
for (int j = 0; y[j] != '\0'; j++)
{
if (strchr(x, y[j]) == 0)
y[j] = '*';
}
Test program
@LooneyTunes asks what happens with: x[] = "apcd"
and y[] = "abcd"
- do you get "a*cd"
.
The answer is yes. Here's a test program that demonstrates the results. As far as I am concerned, it is pure C code, though G++ is quite happy with it too. You might need the C99 option such as '-std=c99
' with GCC set on the compiler. MSVC won't like it if it compiles this as C code; declare j
at the top of the function for it.
#include <string.h>
#include <stdio.h>
static void doit(const char *x, char *y)
{
printf("Before: x = %s, y = %s\n", x, y);
for (int j = 0; y[j] != '\0'; j++)
{
if (strchr(x, y[j]) == 0)
y[j] = '*';
}
printf("After: x = %s, y = %s\n", x, y);
}
int main(void)
{
const char x1[] = "apf";
const char x2[] = "apcd";
char y1[] = "apple";
char y2[] = "abcd";
doit(x1, y1);
doit(x2, y2);
return 0;
}
Output
Before: x = apf, y = apple
After: x = apf, y = app**
Before: x = apcd, y = abcd
After: x = apcd, y = a*cd
This would be easier if you were using the C++ string class, but here's an answer for C strings.
int i = 0;
while (x[i] != '\0' && y[i] != '\0') {
if (x[i] != y[i]) {
y[i] = '*';
}
i++;
}
y[i] = '\0'; // C strings are terminated with the null character
Edit: I noticed you wanted to change the y array rather than create a new one.
精彩评论