如何将字符从一个字符串复制到另一个字符串?

时间:2015-12-01 05:56:19

标签: c arrays xcode string

这是我的代码: -

void sumNumbersInString(char j[100]) {
    int count = 0;
    char list[100];
    int i;
    for (i = 0; i < 100; i++){
        if (j[i] == '0' || j[i] == '1' || j[i] == '2' || j[i] == '3' || j[i] == '4' || j[i] == '5' || j[i] == '6' || j[i] == '7' || j[i] == '8' || j[i] == '9'){
            count++;
            strncpy(list,j, 1);
            printf("%c\n", j[i]);
        }

    }
    printf("Count = %d\n", count);
    printf("Final String: %s\n", list);


}

int main() {
    char s[100] = "hello100supach4ier78hu";
    sumNumbersInString(s);
    return 0;
} 

所以我想做的是一旦我从字符串中分离数字我想把数字放在一个不同的字符串中..我怎么样...... PLz帮助我

3 个答案:

答案 0 :(得分:1)

初始化char list[100] = {0};以打印正确的字符串。

使用赋值语句(不需要strncpy),因为你在字符串中逐个测试char并增加最终列表的指针。

工作代码......

void sumNumbersInString(char j[100]) {
    int count = 0;
    char list[100] = {0};
    int i;
    for (i = 0; i < 100; i++){
        if (j[i] == '0' || j[i] == '1' || j[i] == '2' || j[i] == '3' || j[i] == '4' || j[i] == '5' || j[i] == '6' || j[i] == '7' || j[i] == '8' || j[i] == '9'){

            //strncpy(list,j[i], 1);
           list[count]=j[i];
            count++;
            printf("%c\n", j[i]);
        }

    }
    printf("Count = %d\n", count);
    printf("Final String: %s\n", list);


}

int main() {
    char s[100] = "hello100supach4ier78hu";
    sumNumbersInString(s);
    return 0;
}

答案 1 :(得分:1)

您可以这样做:

list[count] = j[i];
count++;

你也可以使用&#34; isdigit()&#34;在Unix / Linux系统上测试数字。见http://linux.die.net/man/3/isdigit

但是如果你想使用strncpy:

strncpy(list + count, j + i, 1);
count++;

另外,正如@Mohan所指出的那样,确保列表以NULL结尾。您的初始化是正确的,因为只要有终止字符的空间,字符串文字就会以NULL结尾。否则,可以安全地初始化列表:

char list[100] = {0}; 

答案 2 :(得分:0)

应该进行少量修改

void sumNumbersInString(char j[100]) {
    int count = 0;
    char list[100] = {0,}; // clean string
    int i, idx; // idx to keep track of final list length
    for (i = 0, idx = 0; i < 100; i++){

        if ( j[i] >= '0' && j[i] <= '9' ) {
            count++;
        } else {
            list[idx] = j[i];
            idx ++;
        }

    }
    printf("Count = %d\n", count);
    printf("Final String: %s\n", list);


}