Câu hỏi được yêu cầu here rất giống với những gì tôi đang gặp sự cố. Sự khác biệt là tôi phải chuyển một đối số tới một hàm để loại bỏ các khoảng trắng và trả về mảng chuỗi/mảng kết quả. Tôi đã nhận được mã làm việc để loại bỏ các không gian nhưng đối với một số lý do tôi còn lại với các ký tự trailing còn sót lại từ mảng ban đầu. Tôi thậm chí đã thử strncpy nhưng tôi đã có rất nhiều lỗi.Chức năng xóa các khoảng trắng khỏi mảng chuỗi/char trong C
Dưới đây là những gì tôi có cho đến nay:
#include <stdio.h>
#include <string.h>
#define STRINGMAX 1000 /*Maximium input size is 1000 characters*/
char* deblank(char* input) /* deblank accepts a char[] argument and returns a char[] */
{
char *output=input;
for (int i = 0, j = 0; i<strlen(input); i++,j++) /* Evaluate each character in the input */
{
if (input[i]!=' ') /* If the character is not a space */
output[j]=input[i]; /* Copy that character to the output char[] */
else
j--; /* If it is a space then do not increment the output index (j), the next non-space will be entered at the current index */
}
return output; /* Return output char[]. Should have no spaces*/
}
int main(void) {
char input[STRINGMAX];
char terminate[] = "END\n"; /* Sentinal value to exit program */
printf("STRING DE-BLANKER\n");
printf("Please enter a string up to 1000 characters.\n> ");
fgets(input, STRINGMAX, stdin); /* Read up to 1000 characters from stdin */
while (strcmp(input, terminate) != 0) /* Check for que to exit! */
{
input[strlen(input) - 1] = '\0';
printf("You typed: \"%s\"\n",input); /* Prints the original input */
printf("Your new string is: %s\n", deblank(input)); /* Prints the output from deblank(input) should have no spaces... DE-BLANKED!!! */
printf("Please enter a string up to 1000 characters.\n> ");
fgets(input, STRINGMAX, stdin); /* Read up to another 1000 characters from stdin... will continue until 'END' is entered*/
}
}
Bản sao có thể có của [Cách xóa tất cả dấu cách và tab khỏi một chuỗi nhất định bằng ngôn ngữ C?] (Http://stackoverflow.com/questions/1514660/how-to-remove-all-spaces-and -tabs-from-a-given-string-in-c-language) –