如何将其重写为C

如何将其重写为C

如何将其重写为C?

prefix + str.charAt(i)




str.substring(0, i) + str.substring(i+1, len)


我尝试过类似的操作,但是在str[3]上失败了

int len;
//prefix
len = strlen(prefixP);
char prefix[len];
strncpy(prefix, prefixP, len);

//str
len = strlen(strP);
char str[len+1];
strncpy(str, strP, len);

//prefix + znak
len = strlen(prefix) + 1;
char buffer[len];
sprintf(buffer,"%s%s", prefix, str[3]);

printf("%s, %s, %s\n", prefix, str, buffer);




//str.substring(0, i) + str.substring(i+1, len)
char subbuff[i+2];
memcpy(subbuff, str, i+1);
subbuff[i + 1] = '\0';

printf("%s\n", subbuff);

//substring 2
char subbuff2[abs(i-len) + 2];
memcpy(subbuff2, str, abs(i-len) + 1);
subbuff[i + 1] = '\0';*/

最佳答案

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

char *substring(char *outbuff, const char *string, size_t start, size_t end){
    size_t len = end - start;//It does not include characters `end` position.
    strncpy(outbuff, string + start, len);
    outbuff[len] = '\0';
    return outbuff;
}

int main(){
    char *prefix = "the ";
    char *str = "not a list";
    char result[32];
    char sub1[16], sub2[16];
    int i = 4, len = strlen(str);
    //prefix + str.charAt(i)
    sprintf(result, "%s%c", prefix, str[i]);
    printf("%s\n", result);//the a

    //str.substring(0, i) + str.substring(i+1, len)
    strncpy(sub1, str, i);
    sub1[i] = '\0';
    strncpy(sub2, str + i + 1, len - (i+1));
    sub2[len - (i+1)] = '\0';
    sprintf(result, "%s%s", sub1, sub2);
    printf("%s\n", result);//not  list

    sprintf(result, "%s%s", substring(sub1, str, 0, i), substring(sub2, str, i+1, len));
    printf("%s\n", result);//not  list

    return 0;
}

关于java - 如何将其重写为C?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21255180/

10-12 20:30