You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将C语言字符串中的换行符替换为逗号?技术实现问询

Replace Newlines with Commas in C (No Direct String Edit)

Hey there, let's get this sorted. You've got a string with newline characters, and you want to convert all those \n to commas without modifying the original string's declaration—instead, process it to get the clean comma-separated output. Here's how to make it work:

How It Works

We'll loop through every character in the string, check if it's a newline, and swap it out for a comma. Since your string is stored in a mutable array (char str[]), we can safely modify its characters on the fly.

Modified Code

#include <stdio.h>
#include <string.h>

int main(){
    char str[] = "This\nis\na\nsimple\nsentence";
    
    // Loop through each character until we hit the end of the string
    for (int i = 0; str[i] != '\0'; i++) {
        // Replace newline with comma when found
        if (str[i] == '\n') {
            str[i] = ',';
        }
    }
    
    // Print the comma-separated result
    printf("%s\n", str);
    return 0;
}

Quick Notes

  • If your string were a literal (like char* str = "This\nis..."), you couldn't modify it directly—you'd need to copy it to a writable array first. But since you used char str[], we're good to go.
  • The loop stops at the null terminator (\0), which is how C knows where the string ends.
  • Running this code will output exactly what you want: This,is,a,simple,sentence.

内容的提问来源于stack exchange,提问作者Quora Bai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 16:38:15