سؤال

I have a bunch of strings that I need to verify if these have all spaces.

I can do strlen(trim(strct.data)) > 0.

But, it's not null terminated, but the length is known.

i.e. if strct.len is 5 then I need to verify if strct.data has spaces for 5 chars. 6th char is not guaranteed to be null. I have an array of strct each of which can have different length of data to be validated for spaces.

I tried strnlen(trim(strct.data)) and later realized it didn't fix anything as the trim already removed all spaces.

Any ideas other than the obvious looping over each character of strct.data (my last option if there is no other go)?

note: trim is a userdefined function I use to remove leading and trailing spaces. It doesn't stop until the NULL too. I am looking for a way to handle both.

هل كانت مفيدة؟

المحلول

How to ensure the string is full of spaces for a given length?

step 1:

  char buf[MAX_SIZE];
  sprintf(buf,"%*s",MAX_SIZE-1,"");  //fill buffer with spaces

step 2:

Now use strncmp() compare strct.len number of character of strct.data character array with buf

if(strncmp(strct.data ,buf ,strct.len) ==0)
  {
   //all are spaces
  }  

You need not to repeat step1.


Another solution jxh suggested you can also use memset() instead of sprintf()

  memset(buf, ' ', sizeof buf); //fill buf with all spaces 

You need do this once, next time onwards you need not do this.


You can also use VLA.

declaring char buf[strct.len];

but you need to use memset each time.

نصائح أخرى

Probably the best is doing the looping yourself:

for(int i=0; i<strct.len; ++i) {
  if(strct[i] != ' ') {
    return false;
  }
}
return true;

As the character array is not null terminated, it is not a string.
But let's not quibble on that point and make a fast routine for large arrays.

IsCharArrayAllSpace(const char *p, size_t Length) {
  if (Length < 1) return 1;  // TBD: decide how to handle the zero-length case
  return (p[0] == ' ') && (memcmp(p, &p[1], Length-1) == 0);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top