简体   繁体   中英

how to alternating two string characters in c language

for example: s1 = "ABC"

s2 = "qwerty"

s3 will be "AqBwCerty"

and let all be upper letter

it will be"AQBWCERTY"

how to create it?

thank you~

this is my current code in the main function:

char w[100];
char s[50] = "abcderf";
char t[50] = "ARTYY";
int len = strlen(s);
int len1 = strlen(t);
int i, j;
if (len > len1) {
    t[50] + s[50];
}
printf("%s", w);

Try sth like this:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* interleaveStr(char* s1, char* s2) {
    char* space = malloc(strlen(s1) + strlen(s2) + 1);
    char* newStr = space;
    int turn = 0;
    while (*s1 && *s2) {
        *newStr++ = !turn ? *s1++ : *s2++;
        turn = !turn;
    }

    while (*s1) {
        *newStr++ = *s1++;
    }
    while (*s2) {
        *newStr++ = *s2++;
    }
    *newStr = '\0';
    return space;
}

int main() {
    char* s1 = "ABC";
    char* s2 = "qwerty";
    char* inter = interleaveStr(s1, s2);
    printf("%s\n", inter);
    free(inter);
}
#include <stdio.h>
#include <string.h>

void alternate_2_strings(char *s1, char *s2, char *out)
{
    while(*s1 != '\0' && *s2 != '\0') {
        *out++ = *s1++;
        *out++ = *s2++;
    }
    strcpy(out, s2);
}

int main()
{
    char w[100];
    char s[] = "abcderf";
    char t[] = "ARTYY";
    alternate_2_strings(t,s,w);
    printf("%s\n", w);
    return 0;
}
#include<stdio.h>
#include<string.h>

int main(){
int i,j;
char string_one[100];
char string_two[50]="ASDF";
char string_three[50]="anands";
int len_two=strlen(string_two);
int len_three=strlen(string_three);
if(len_two<=len_three){
    for(i=0;i<len_two;i++){
        string_one[i*2]=string_two[i];
        string_one[i*2+1]=string_three[i];
    }
    for(j=i*2;i<len_three;i++,j++){
        string_one[j]=string_three[i];  
    }
    string_one[j]='\0';
}
else{
    for(i=0;i<len_three;i++){
        string_one[i*2]=string_two[i];
        string_one[i*2+1]=string_three[i];
    }
    for(j=i*2;i<len_two;i++,j++){
        string_one[j]=string_two[i];    
    }
    string_one[j]='\0';

}
puts(string_two);
puts(string_three);
puts(string_one);
puts(strupr(string_one));
return 0;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM