如何将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 usedchar 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
相关产品推荐
相关产品推荐

