简体   繁体   English

在C中逐个字符读取一个字符串

[英]Reading a string character by character in C

I am trying to read a string character by character in C. Since there is no string class, there are no functions to help this. 我试图在C中逐个字符地读取一个字符串。由于没有字符串类,因此没有函数可以帮助实现这一点。 Here is what i want to do: I have, 这是我想做的:我有,

char m[80];  //I do some concenation, finally m is:

m= 12;256;2;

Now, i want to count how many characters are there between the semicolumns. 现在,我要计算半列之间有多少个字符。 In this example, there are 2,4 and 1 characters respectively. 在此的示例分别有2,4和1个字符。 How can do this? 怎么办

Thank you 谢谢

What do you mean "there are no functions to help this"? 您是什么意思,“没有任何功能可以帮助您”? There are. 有。 If you want to read a string, check out the function fgets . 如果要读取字符串,请签出fgets函数。

On to the problem at hand, let's say you have this: 关于当前的问题,假设您有以下问题:

char m[80] = "12;256;2";

And you want to count the characters between the semi-colons. 并且您想计算分号之间的字符。 The easiest way is to use strchr . 最简单的方法是使用strchr

char *p = m;
char *pend = m + strlen(m);
char *plast;
int count;

while( p != NULL ) {
    plast = p;
    p = strchr(p, ';');

    if( p != NULL ) {
        // Found a semi-colon.  Count characters and advance to next char.
        count = p - plast;
        p++;
    } else {
        // Found no semi-colon.  Count characters to the end of the string.
        count = pend - p;
    }

    printf( "Number of characters: %d\n", count );
}

Well I'm not sure were supposed to write the code for you here, just correct it. 好吧,我不确定应该在这里为您编写代码,只是对其进行更正。 But... 但...

int strcount, charcount = 0, numcharcount = 0, num_char[10] = 0;  
                                            //10 or how many segments you expect

for (strcount = 0; m[strcount] != '\0'; strcount++) {

    if (m[strcount] == ';') {

         num_char[numcharcount++] = charcount;
         charcount = 0;             

    } else {

         charcount++;

    }

}

This will store the amount of each character between the ; 这将存储之间的每个字符的数量; in an array. 在一个数组中。 It is kind of sloppy I'll admit but it will work for what you asked. 我承认这有点草率,但可以满足您的要求。

If you don't mind modifying your string then the easiest way is to use strtok . 如果您不介意修改字符串,那么最简单的方法是使用strtok

#include <string.h>
#include <stdio.h>
int main(void) {
    char m[80] = "12;256;2;";
    char *p;

    for (p = strtok(m, ";"); p; p = strtok(NULL, ";"))
        printf("%s = %u\n", p, strlen(p));
}

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

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