简体   繁体   English

在C中没有分割功能的分割字串

[英]Split string without split function in c

So I'm writing a program that takes a persons name and splits it into their first and last name so for example if you enter JonSnow it should print: First: Jon Last: Snow 因此,我正在编写一个程序,该程序使用一个人的名字并将其分解为名字和姓氏,例如,如果您输入JonSnow,则应打印:First:Jon Last:Snow

This is the code, please ignore the comments, I was testing a bunch of different ways to do it. 这是代码,请忽略注释,我正在测试一堆不同的方法。

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

int main()    
{   
    char name[50],first[25],last[25];
    int i;

    printf("What is your name? ");
    scanf("%s",name);

    strcpy(first," ");
    strcpy(last," ");
    for(i=0;i<strlen(name);i++){
        strcat(first,name[i]);              //for(j=i+1;strlen(name);j++){
        if(name[i+1]>=65 && name[i+1]<=90){
            strcat(last,name[i]);
            strcat(last,name[i+1]); 
        }
        //}             
    }

    printf("First name: %s \n",first);
    printf("Last name: %s \n",last);  
}

When I run it in the terminal, I get this: 当我在终端中运行它时,得到以下信息:

What is your name? JonSnow

Segmentation fault (core dumped)

What is the problem, please help... 有什么问题,请帮忙...

I think your code is close, you're just messing up how to use strcat trying to add a single character to the end of a string, which it doesn't do. 我认为您的代码很接近,您只是在弄乱如何使用strcat尝试在字符串的末尾添加单个字符,而这样做却没有。 Perhaps you can do something like this: 也许您可以执行以下操作:

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

int main() {

char name[50],first[25] = {0},last[25] = {0};
int i;

    printf("What is your name? ");
    scanf("%s",name);

    for(i=0;i<strlen(name);i++) {
        if(name[i+1]>=65 && name[i+1]<=90) {
            strncpy(first,name,i+1);
            strcpy(last,&name[i+1]); 
        }
    }
    printf("First name: %s \n",first);
    printf("Last name: %s \n",last);
}

strncpy copies the number of characters specified by i+1 into first. strncpy将i + 1指定的字符数复制到第一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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