[英]Trying to reverse a string without using string.h library functions in C using pointers
[英]C : trying to remove spaces from a string without using any string library functions
所以我试图找出一种方法来打印一个没有空格的字符串,但由于某种原因它不起作用,每当我在程序中输入一个字符串时,它最终什么都不打印。
#include <stdio.h>
char *removeSpaces(char *inString);
int main() {
char str1[50];
printf("Enter a string : ");
scanf("%s", &str1);
removeSpaces(str1);
}
char *removeSpaces(char *inString) {
char str2[50];
int j = 0;
for (int i = 0; i < 50; i++) {
if (inString[i] != ' ') {
str2[j] = inString[i];
j++;
}
}
for (int i = 0; i < 50; i++) {
printf("%s", str2[i]);
}
}
您还可以使用指针遍历 memory 位置,测试每个 position 是否有不需要的char
值,这是您的 function 修改为使用该方法:
char *removeSpaces(char *inString);// your original prototype
char *remove_char(char *inString, char c);//generalized
int main(void) {
//use suggestions in other answer for correct user input
const char str1[] = {"this is a string with spaces"};//for simple illustration
printf("%s\n", removeSpaces(str1));
printf("%s\n", remove_char(str1, ' '));
return 0;
}
char *removeSpaces(char *inString)// your original prototype
{
if(!inString) return (char *)"bad input";
char *from; // "read" pointer
char *to; // "write" pointer
from = to = inString; // init both read and write pointers to original string
while (*from)
{
if( (*from != ' ') && (*from != '\t') && (*from != '\n'))
{
*to++ = *from;
}
from++;
}
*to = 0;
return inString;// add a return statement to return the char *
}
//optionally, create your function to remove any unwanted character
char *remove_char(char *inString, char c)//generalized
{
char *from; // "read" pointer
char *to; // "write" pointer
from = to = inString; // init both read and write pointers to original string
while (*from)
{
if (*from != c)
{
*to++ = *from;
}
from++;
}
*to = 0;
return inString;// add a return statement to return the char *
}
输入方式错误
下面不会扫描到str1
任何带有空格的东西。
// bad
char str1[50];
scanf("%s", &str1);
相反,使用fgets()
读取一行并形成一个字符串。
char str1[50];
if (fgets(str1, sizeof str, stdin)) {
// success!
如果需要,去掉潜在的尾随'\n'
。
str1[strcspn(str1, "\n")] = '\0';
读取字符串末尾
循环读取数组的大小。 它应该循环到null 字符。
// for (int i = 0; i < 50; i++)
for (int i = 0; inString[i]; i++)
缺少\0
str2[]
中的字符串形成不完整,因为它缺少null 字符'\0'
。
str2[j] = '\0'; // add after the loop
警告未完全启用
下面应该警告"%s"
与str2[i]
不匹配。
for (int i = 0; i < 50; i++) {
printf("%s", str2[i]);
}
相反,没有循环。
printf("%s", str2);
这是在这里学到的最大的教训。 通过完全启用警告,编译器可以快速提供错误或有问题的反馈; 比 Stackoverflow 快。
缺少退货
char *removeSpaces(char *inString)
应该返回一个char *
,但是代码缺少return something;
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.