[英]Removing a newline from the middle of a string using getchar
現在我有一個看起來像這樣的字符串:
A sentence
with a newline.
我正在通過控制台輸入讀取字符串,如下所示:
ch = getchar();
while (ch != '.') {
msg[i] = ch;
i++;
ch = getchar();
}
並且,在讀入它之后,我通過在 function 中執行此操作並應用於msg
char 數組來刪除存在的空格:
char *remove_white_spaces(char *str) {
int i = 0, j = 0;
while (str[i]) {
if (str[i] != ' ')
str[j++] = str[i];
i++;
}
str[j] = '\0';
return str;
}
我嘗試循環遍歷它並在\n
處停止,但這會留下“Asentence”的 output,因為字符串在\n
設置為 0 時終止。
整體主線:
int main(void) {
char msg[MAX_MSG_LEN+1];
char ch;
int i = 0;
ch = getchar();
while (ch != '.') {
msg[i] = ch;
i++;
ch = getchar();
}
msg[i] = '.';
msg[i + 1] = '\0';
remove_white_spaces(msg);
printf("%s\n", msg);
return 0;
}
您可以使用isspace
function來測試和跳過任何/所有空白字符,包括普通空格和換行符:
#include <ctype.h> // For definition of "isspace"
char *remove_white_spaces(char *str) {
int i = 0, j = 0;
while (str[i]) {
if (!isspace((unsigned char)(str[i])))
str[j++] = str[i];
i++;
}
str[j] = '\0';
return str;
}
關於將參數轉換為isspace
為unsigned char
的原因,請參閱此討論。
Function 刪除和替換字符串中的任何字符。
toRemove
- 要刪除的字符addSpace
- 替換為空格allowMultiple
- 替換更多相鄰時允許多個空格allowEdges
- 允許在開頭和結尾添加空格char *removeChars(char *str, const char *toRemove, const int addSpace, const int allowMultiple, int const allowEdges)
{
char *rd = str, *wr = str;
int replaced = 0;
if(rd)
{
while(*rd)
{
if(strchr(toRemove, *rd))
{
if(addSpace)
{
if(!replaced || allowMultiple)
{
if(wr != str || (wr == str && allowEdges))
{
*wr++ = ' ';
replaced = 1;
}
}
}
}
else
{
*wr++ = *rd;
replaced = 0;
}
rd++;
}
if(allowEdges) *wr = 0;
else
while((wr - 1) > str)
{
if(*(wr - 1) == ' ') {*(wr - 1) = 0; wr--;}
else break;
}
}
return str;
}
int main(void)
{
char str[] = "%%%%%A sentence\n\n\nwith!@#$%^a newline.%%%%%%%";
printf("`%s`\n", removeChars(str,"\n!@#$%^", 1, 0, 0));
}
按照@MarkBenningfield 的建議,我執行了以下操作並檢查了 '\n' 並將其替換為空格。
while (ch != '.') {
msg[i] = ch;
i++;
ch = getchar();
if (ch == '\n') {
ch = ' ';
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.