在不带指针的C-string中复制单个字符

Copy single characters in C-string without pointers

本文关键字:复制 单个 字符 C-string 指针      更新时间:2023-10-16

赋值:

创建一个包含姓名、年龄和标题的Cstring变量。每个字段由一个空格分隔。例如,字符串可能包含"Bob 45"程序员"或任何其他相同格式的姓名/年龄/头衔。编写一个程序从cstring(不是类string)中提取名称的函数,

我从字符串中提取了名称,但在此之后我遇到了任何字符的麻烦。我不能用指针,因为我们还没学过,所以不能用笔划。我只需要一个方向,因为我确定有一个函数可以使它更简单。谢谢你。

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    char y[] = "taylor 32 dentist";
    char name[25];
    char age[4];
    char title[40];
    int i = 0;
    while (y[i] != ' ')
    {
        while (y[i] != '')
        {
            if (y[i] == ' ' || y[i + 1] == '')
            {
                break;
            }
            name[i] = y[i];
            i++;
        }
    }
    cout << "Name: " << name << endl
         << "Age: " << age << endl
         << "Title: " << title << endl;
    return 0;
}

解决:

#include <iostream>
#include <cstring>
using namespace std;
void separate_Variables(char y[], char name[], char age[], char title[]);
void output(char name[], char age[], char title[]);
int main()
{
    char y[] = "taylor 32 dentist";
    char name[25];
    char age[4];
    char title[40];
    separate_Variables(y, name, age, title);
    output(name, age, title);
    return 0;
}
void separate_Variables(char y[], char name[], char age[], char title[])
{
    int i = 0;
    int j = 0;
    while (y[i] != '' && y[i] != ' ') {
        name[j++] = y[i++];
    }
    name[j] = '';
    j = 0;
    i++;
    while (y[i] != '' && y[i] != ' ') {
        age[j++] = y[i++];
    }
    age[j] = '';
    j = 0;
    i++;
    while (y[i] != '' && y[i] != ' ') {
        title[j++] = y[i++];
    }
    title[j] = '';
    j = 0;
}
void output(char name[], char age[], char title[])
{
    cout << "Name: " << name << endl
         << "Age: " << age << endl
         << "Title: " << title << endl;
}

您不需要嵌套循环-您所需要的只是三个循环一个接一个。

循环看起来是一样的:取i -th字符,将其与空格进行比较,并存储在三个目的地之一。当您看到空格时,将其替换为'',并继续到下一个目的地:

int j = 0;
while (y[i] != '' && y[i] != ' ') {
    name[j++] = y[i++];
}
name[j] = ''; // Add null terminator
j = 0;          // Reset j for the next destination
i++;            // Move to the next character in y[]
... // Do the same thing for age and title

外环需要测试''

内部循环(现在是!= ' ')可以为每个字段复制。您需要一个单独的索引变量来分隔i表示y,并将它放在字段(fi?)