我有一个用破折号替换空格的程序。现在我需要能够计算已被替换的空间量并打印出来。这是我对间距替换的编码。
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main()
{
char string[100], *space;
{
printf("Enter a string here: \n"); //Enter a string in command prompt
fgets(string, sizeof(string), stdin); //scans it and places it into a string
space = string;
while (*space == ' '? (*space = '-'): *space++);
printf("%s\n", string);
}
getchar();
}
这是计算空间数的代码。
#include <iostream>
#include <string>
int count( const std::string& input )
{
int iSpaces = 0;
for (int i = 0; i < input.size(); ++i)
if (input[i] == ' ') ++iSpaces;
return iSpaces;
}
int main()
{
std::string input;
std::cout << "Enter text: ";
std::getline( std::cin, input );
int numSpaces = count( input );
std::cout << "Number of spaces: " << numSpaces << std::endl;
std::cin.ignore();
return 0;
}
我不确定如何把2组合在一起?有人可以帮忙吗?
更新
我已将代码更改为以下内容:
#include <stdio.h>
#include <conio.h>
#include <string.h>
int numSpaces = 0;
int main()
{
char string[100], *space;
{
printf("Enter a string here: \n"); //Enter a string in command prompt
fgets(string, sizeof(string), stdin); //scans it and places it into a string
space = string;
while (*space == ' '? (*space = '-'): *space++);
printf("%s\n", string);
}
while (*space)
{
if( *space == ' ')
{
*space = '-';
++numSpaces;
}
++space;
printf("%f\n", numSpaces);
}
getchar();
}
结果有问题。我不断加载零点
答案 0 :(得分:1)
您可以在循环中使用类std :: string的成员函数替换,也可以使用应用于字符串的标准算法替换。至于我,我会选择标准的算法。
例如
std::replace( input.begin(), input.end(), ' ', '-' );
答案 1 :(得分:0)
要继续使用c,请相应地延长while循环:
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main()
{
char string[100], *space;
int numSpaces = 0;
printf("Enter a string here: \n"); //Enter a string in command prompt
fgets(string, sizeof(string), stdin); //scans it and places it into a string
space = string;
// Replacement and counting are done within the following loop IN ONE GO!
while (*space)
{
if( *space == ' ')
{
*space = '-';
++numSpaces;
}
++space;
}
printf("%s\n", string);
printf("Replaced %d space characters\n", numSpaces);
getchar();
}
答案 2 :(得分:0)
要保持第一个片段的精神:
int replaced = 0;
while (*space == ' '? (replaced++, *space++ = '-'): *space++);