这是我在这个论坛上的第一篇文章,请耐心等待。
我需要做一个简短的程序,在那里用户可以输入2个字符串,应该附加后。我已经得到了下面的代码(我不被允许使用其他的“包含”)。
我需要知道的是:我如何才能拒绝用户输入的任何空格?
示例: 1. String "Hello“| 2. String "World”
结果应该是"HelloWorld“而不是"Hello World”。
#include <stdio.h>
void main()
{
char eingabe1[100];
char eingabe2[100];
int i = 0;
int j = 0;
printf("Gib zwei Wörter ein, die aneinander angehängt werden sollen\n");
printf("1. Zeichenkette: ");
gets(eingabe1);
printf("\n");
printf("2. Zeichenkette: ");
gets(eingabe2);
printf("\n");
while (eingabe1[i] != '\0')
{
i++;
}
while (eingabe2[j] != '\0')
{
eingabe1[i++] = eingabe2[j++];
}
eingabe1[i] = '\0';
printf("Nach Verketten: ");
puts(eingabe1);
}发布于 2016-01-08 15:55:56
在复制字符串时,必须过滤掉空格。
您有两个字符串索引,第一个字符串为i,第二个字符串为j。如果将i用于读取位置(两个字符串随后都可以使用;您可以在独立循环中“重用”循环计数器),并将j用于写入位置,则可以更好地利用这些索引。
下面是如何实现的。请注意,代码试图通过仅在字符串中有空格时添加字符来防止缓冲区溢出。只有在复制第二个字符串时才需要执行此检查,因为在处理第一个字符串时执行j <= i。
#include <stdio.h>
int main()
{
char str1[100] = "The quick brown fox jumps over ";
char str2[100] = "my big sphinx of quartz";
int i = 0;
int j = 0;
while (str1[i] != '\0') {
if (str1[i] != ' ') str1[j++] = str1[i];
i++;
}
i = 0;
while (str2[i] != '\0') {
if (str2[i] != ' ' && j + 1 < sizeof(str1)) str1[j++] = str2[i];
i++;
}
str1[j] = '\0';
printf("'%s'\n", str1);
return 0;
}发布于 2016-01-08 16:22:12
/**
return: the new len of the string;
*/
int removeChar(char* string, char c) {
int i, j;
int len = strlen(string)+1; // +1 to include '\0'
for(i = 0, j = 0 ; i < len ; i++){
if( string[i] == c )
continue; // avoid incrementing j and copying c
string[ j ] = string[ i ]; // shift characters
j++;
}
return j-1; // do not count '\0';
}
int main(){
char str1[] = "sky is flat ";
char str2[100] = "earth is small ";
strcat( str2, str1 );
printf("with spaces:\n\t'%s'\n", str2) ;
removeChar(str2, ' ');
printf("without spaces:\n\t'%s'\n", str2 );
}
/**
BONUS: this will remove many characters at once, eg "\n \r\t"
return: the new len of the string;
*/
int removeChars(char* string, char *chars) {
int i, j;
int len = strlen(string);
for(i = 0, j = 0 ; i < len ; i++){
if( strchr(chars,string[i]) )
continue; // avoid incrementing j and copying c
string[ j ] = string[ i ]; // shift characters
j++;
}
string[ j ]=0;
return j;
}发布于 2016-01-08 18:11:54
感谢所有人的回答。我现在找到解决方案了。
我从你那里读到了一些建议,并将努力记住未来。
请看下面的代码:(请原谅变量的奇怪名称,我使用的是德语单词)
几点注意事项:我不能使用库函数,作为一个实习生,我不能使用fgets。
#include <stdio.h>
void main()
{
char eingabe1[100];
char eingabe2[100];
int i = 0;
int j = 0;
printf("gib zwei wörter ein, die aneinander angehängt werden sollen\n");
printf("1. zeichenkette: ");
gets(eingabe1);
printf("\n");
printf("2. zeichenkette: ");
gets(eingabe2);
printf("\n");
//Attach Strings
while (eingabe1[i] != '\0')
{
i++;
}
while (eingabe2[j] != '\0')
{
eingabe1[i++] = eingabe2[j++];
}
//Remove Space
eingabe1[i] = '\0';
i = 0;
j = 0;
while (eingabe1[i] != '\0')
{
if (eingabe1[i] != 32)
{
eingabe2[j++] = eingabe1[i];
}
i++;
}
eingabe2[j] = '\0';
printf("Nach verketten: ");
puts(eingabe2);
}https://stackoverflow.com/questions/34671814
复制相似问题