【发布时间】:2020-12-31 00:03:16
【问题描述】:
这是来自 C 第 4 版编程第 9 章的练习。该程序是将字符读入字符串,并通过指定起始位置和字符数将字符串的一部分提取为子字符串。 程序编译和运行良好,除非源的第零位被声明为开始。然后什么都没有显示。 这是我的代码。
/* Programme to extract a portion from a string using function
sub-string (source, start, count, result) ex9.4.c
ALGORITHM
Get text input into a char array (declare to be fixed size);
Determine length of source string;
Prepare result array to be dynamic length using desired count + 1;
Copy from source array into result array
*/
#include <stdio.h>
#include <stdbool.h>
#define MAX 501
void read_Line (char buffer[]);
int string_Length (char string[]);
void sub_String (char source[], int start, int count, char result[]);
int main(void)
{
char strSource[MAX];
bool end_Of_Text = false;
int strCount = 0;
printf("This is a programme to extract a sub-string from a source string.\n");
printf("\nType in your text (up to 500 characters).\n");
printf("When you are done, press 'RETURN or ENTER'.\n\n");
while (! end_Of_Text)
{
read_Line(strSource);
if (strSource[0] == '\0')
{
end_Of_Text = true;
}
else
{
strCount += string_Length(strSource);
}
}
// Declare variables to store sub-string parameters
int subStart, subCount;
char subResult[MAX];
printf("Enter start position for sub-string: ");
scanf(" %i", &subStart);
getchar();
printf("Enter number of characters to extract: ");
scanf(" %i", &subCount);
getchar();
// Call sub-string function
sub_String(strSource, subStart, subCount, subResult);
return 0;
}
// Function to get text input
void read_Line (char buffer[])
{
char character;
int i = 0;
do
{
character = getchar();
buffer[i] = character;
++i;
}
while (character != '\n');
buffer[i - 1] = '\0';
}
// Function to count determine the length of a string
int string_Length (char string[])
{
int len = 0;
while (string[len] != '\0')
{
++len;
}
return len;
}
// Function to extract substring
void sub_String (char source[], int start, int count, char result[])
{
int i, j, k;
k = start + count;
for (i = start, j = 0; i < k || i == '\0'; ++i, ++j)
{
result[j] = source[i];
}
result[k] = '\0';
printf("%s\n", result);
}
我在 Linux Mint 上使用 Code::Blocks。
【问题讨论】:
-
强烈建议:在调试器中逐步检查您的代码以解决“出了什么问题”:dummies.com/programming/c/…
-
仅供参考,您的子字符串算法中的
result[k] = '\0';应该是result[j] = '\0'; -
Nit:这可能不会影响您询问的情况,但在 sub_String() 中,循环条件
i < k || i == '\0'不太正确。它应该是 && 而不是 ||,并且你想要source[i] != '\0',而不是i == '\0'。 -
既然你已经提供了一个自我回答,你可能应该从问题中删除答案。