simplest way to print out every other character from a string in C? I already tried to loop through the array using
int main (void)
for(int i = 0; i < strlen(input); i+=2)
{
word[i] += input[i];
}
Why don't you just print it inside the loop?
for(int i = 0; i < strlen(input); i+=2)
{
putchar(input[i]);
}
If you want to copy only each 2nd char into another array, your mistake is using the same index word[i] += input[i];
and as @bcperth mentioned, also using the += operator instead of a regular assignment '='
What you should have done is:
word[i/2] = input[i];
#include <stdio.h>
#include <string.h>
int main(void) {
char* p = "hello world";
char s[32] = "";
for(int i = 0; i < strlen(p); i+=2){
putchar(p[i]);
s[i/2]=p[i];
}
printf("\n\n2nd option\n%s", s);
return 0;
}
Output:
hlowrd
2nd option
hlowrd
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.