简体   繁体   English

通过获取字符来存储字符串

[英]Storing a string by obtaining chars

I'm developing an application in C which requires me to take in a string by building it with a series of chars. 我正在用C开发一个应用程序,它要求我通过用一系列字符构建它来接收字符串。 The chars are taken in via: ch = fgetc(in_file); 字符取自via: ch = fgetc(in_file); and are either a uppercase or lowercase letter. 并且是大写或小写字母。 I want to be able to take a series of chars (such as "bu N ny") and assemble them into a string that I can print, store into another file or compare to another string (such as "buNny"). 我希望能够获取一系列字符(例如“bu N ny”)并将它们组合成一个我可以打印的字符串,存储到另一个文件中或与另一个字符串比较(例如“buNny”)。 How can I do this in C? 我怎么能在C中这样做?

Seems like what you could do is allocate a char array and put the chars in it, keeping track of where you're at in the buffer so you know where to put the next one. 看起来你可以做的就是分配一个char数组并将chars放入其中,跟踪你在缓冲区中的位置,这样你就知道下一个放在哪里。 (Don't forget to maintain the \\0 at the end, if your string needs to be a valid string after each character is added and not just when everything is done.) You need to keep track of your char array's size so you can tell when it's full by comparing where you're at to the size. (不要忘记在最后维护\\0 ,如果你的字符串在添加每个字符后需要是一个有效的字符串,而不是只在完成所有内容时。)你需要跟踪你的char数组的大小,这样你就可以通过比较你所处的大小来判断它何时满了。 When it gets too full, realloc it to a larger size and carry on. 当它太满时,将它重新分配到更大的尺寸并继续。

A common thing to do is to double the size of your buffer every time - that keeps the number of times you need to realloc relatively small (compared to the total length of the string). 常见的做法是每次将缓冲区的大小加倍 - 这使得重新分配所需的次数相对较小(与字符串的总长度相比)。 Of course, choosing a good initial value for the size of your buffer can help a lot. 当然,为缓冲区大小选择一个好的初始值可以提供很多帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM