您的\n
字符串中的 是一个转义序列,由一个字符表示。
你的代码应该是这样的:
int main(void)
{
char str[] = "Hi\n, How are you \n, are you okay\n";
char *strPtr = str;
int i, j;
int count=0;
for(i = 0; str[i]!='\0'; ++i)
{
if (`\n` == str[i]) ++count;
}
strPtr = malloc(i + 1 + count);
for(i = j = 0; str[i]!='\0'; ++i)
{
if ('\n' == str[i]) strPtr[j++] = `\r`;
strPtr[j++] = str[i];
}
strPtr[j] = 0;
printf("This many times we changed it", count);
}
编辑
当您决定更改问题时(顺便说一句 - 只需添加问题以进行澄清,而不是删除原始 OP 的大量内容,因为答案对未来的访问者没有任何意义) - 这是代码:
int main(void)
{
char str[] = "Hi\r\n, How are you \r\n, are you okay\r\n";
int i, j;
for (i = j = 0; 0 != str[i]; ++i)
{
if ('\r' == str[i] && '\n' == str[i + 1])
{
++count;
}
else
{
str[j++] = str[i];
}
}
str[j] = 0;
.. etc - str is without \r\n but \n, count is the number of lines.