我正在尝试解决 C 中的一个问题,即我获取一个字符串并将字符串的某些部分转换为数字。我创建了一个名为“替换”的函数。在函数中,我迭代字符串数组,寻找特定的元音并返回一个数字。结果应该是新字符串。然后我应该调用 main 中应该显示结果的函数。我是 c 方面的大佬,除了使用数组和函数之外,我们没有讨论过其他解决方案。
但是我的代码返回 null。有人可以帮我吗?我现在的结果是猜测工作,不知道我需要做什么,并且花了几个小时......
#include <cs50.h>
#include <stdio.h>
#include <string.h>
string replace(string argv[]);
int main(int argc, string argv[])
{
// argv[1] is the first word at the command line
string s;
string result = 0;
if (argc != 2)
{
printf("Usage: %s word\n", argv[0]);
return 1;
}
else
{
printf("Word is: %s\n", argv[1]);
printf("%s\n", result);
return 0;
}
}
string replace(string argv[])
{
string s = argv[1];
int len = strlen(s);
string result = 0;
for (int i = 0; i < len; i++)
{
if (s[i] == 'a')
{
result += 6;
}
else if (s[i] == 'e' )
{
result += 3;
}
else if (s[i] == 'i')
{
result += 0;
}
else if (s[i] == 'u')
{
result += 'u';
}
else
{
result += s[i];
}
}
return result;
}
我尝试检查我的代码和各种选项来返回字符串。我尝试使用边缘聊天 GPT 来解决我的代码中的问题,但我无法解决问题和代码,现在我什至对调用函数和使用命令行参数的逻辑都感到非常困惑......
result += 3; result += 'u';
等不要向字符串添加任何内容。它不是 C++、Python 或 PHP。
string
只是一个 typedef
隐藏指向 char 的指针。
要创建新字符串,您需要分配足够的内存来容纳所有字符和空字符终止符。
很难理解
result += 3
想要做什么 - 我假设你想将它与 "3"
连接起来。
string replace(string argv[])
{
string s = argv[1];
size_t len = strlen(s);
string result = malloc(len + 1);
if(result)
{
for (int i = 0; i < len; i++)
{
if (s[i] == 'a')
{
result[i] = '6';
}
else if (s[i] == 'e' )
{
result[i] = '3';
}
else if (s[i] == 'i')
{
result[i] = '0';
}
else if (s[i] == 'u')
{
result[i] = 'u'; // for what reason?? (same as OP code)
}
else
{
result[i] = s[i];
}
}
result[len] = 0;
}
return result;
}
但是你永远不会调用这个函数。你需要:
int main(int argc, string argv[])
{
// argv[1] is the first word at the command line
string s;
string result;
if (argc != 2)
{
printf("Usage: %s word\n", argv[0]);
return 1;
}
else
{
printf("Word is: %s\n", argv[1]);
result = replace(argv);
if(result) printf("%s\n", result);
else {/* handle allocation error*/}
free(result);
return 0;
}
}