Segmentation fault in alphabet counter function - c

I am writing a C program that's supposed to take a char array and then count all the lowercase letters in it, all the uppercase letters in it as well as all the vowels.
For some reason though, it's not running because the compiler returns a segmentation fault.
I don't know what it is and I don't know where the problem is
#include <stdio.h>
int lccount(char x[10]){
int count=0,i,j;
char lowalphabet[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
for(i=0;i<=10;i++){
for(j=0;j<=26;j++){
if(x[i]==lowalphabet[j]){
count++;
}
}
}
return count;}
int uccount(char x[10]){
int count=0,i,j;
char upalphabet[]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
for(i=0;i<=10;i++){
for(j=0;j<=26;j++){
if(x[i]==upalphabet[j]){
count++;
}
}
}
return count;}
int vcount(char x[10]){
int count=0,i,j;
char vowels[]={'a','e','i','o','u','A','E','I','O','U'};
for(i=0;i<=20;i++){
for(j=0;j<=10;j++){
if(x[i]==vowels[j]){
count++;
}
}
}
return count;
}
void main(){
char x[10]={'a','W','E','R','s','d','a','e','i','A'};
int v,uc,lc;
v=vcount(x[]);
uc=uccount(x[]);
lc=lccount(x[]);
printf("%d vowels\n%d uppercase\n%dlowercase",v,uc,lc);
}
Result => segmentation fault

First of all, your main() signature is non-standard.
Secondly, you pass arrays as params only with their identifiers.
int main(int argc, char *argv[])
{
char x[10]={'a','W','E','R','s','d','a','e','i','A'};
int v,uc,lc;
v=vcount(x);
uc=uccount(x);
lc=lccount(x);
printf("%d vowels\n%d uppercase\n%dlowercase",v,uc,lc);
return 0;
}
Keep in mind there are a lot of other problems in your code. For example the fact it shows 8 lowercase when in fact there are 6. Check the comments the others posted in your question regarding loops as a hint to fix it.

As others pointed out in the comments, your code has a buffer overflow. Arrays in C are indexed starting from 0, which means that, if you have an array of (say) 26 characters, the first character is at position 0, the second at position 1, ..., the ith at position i-1, the 26th at position 25:
for (int i = 0; i < 25; ++i)
...
And you don't pass a string to a function with [].
Also, your main() declaration is not correct. It should be either one of these:
int main(int argc, const char *argv[]) if you use arguments from the command line, or
int main(void) otherwise.
There are a couple of things you can do to improve your code:
You can avoid allocating an array of chars and the nested for loop if you compare the ith character with its ASCII code.
You can pass the size of the array/string you want to process as a function argument.
Always use const when you don't modify your data.
int lccount(const size_t size, const char x[size])
{
int count = 0;
for (size_t i = 0; i < size; ++i)
if (x[i] >= 'a' && x[i] <= 'z')
++count;
return count;
}
int uccount(const size_t size, const char x[size])
{
int count = 0;
for (size_t i = 0; i < size; ++i)
if (x[i] >= 'A' && x[i] <= 'Z')
++count;
return count;
}
int vcount(const size_t size, const char x[size])
{
int count = 0;
for (size_t i = 0; i < size; ++i)
switch (x[i]) {
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'u': case 'U':
++count;
break;
default: continue;
}
return count;
}
int main(void) // Since you don't use argc and argv
{
char x[10] = {'a', 'W', 'E', 'R', 's', 'd', 'a', 'e', 'i', 'A'};
const size_t size = sizeof(x) / sizeof(x[0]);
int v = vcount(size, x);
int uc = uccount(size, x);
int lc = lccount(size, x);
printf("%d vowels\n%d uppercase\n%d lowercase",v, uc, lc);
}
Result:
6 vowels
4 uppercase
6 lowercase

Related

Create function which copy all values from one char array to another char array in C (segmentation fault)

I have a task. I must copy all values form one char array (sentence[]) to another empty char array sentence2[]), but I don't know why I get segmentation fault. They told us also that we must create own strlen function to check how long is string.
This is my code
#include <stdio.h>
#include <stdlib.h>
int new_strlen (char *tab)
{
int i;
for (i = 0; tab[i] != '\0'; ++i);
return i;
}
int copyText(char from[],char to[],int max)
{
int i, j;
if (new_strlen(from) <= max)
{
for(int i = 0; i != '\0'; i++) {
to[i] = from[i];
}
to[i+1] = '\0';
}
return 0;
}
int main (int argc, char *argv[])
{
char sentence[] = "C is \n a \n programming \t language";
char sentence2[1000];
copyText(sentence, sentence2, 1000);
printf("Show my array: %s \n", sentence2);
return 0;
}
Here are the bugs:
int copyText(char from[],char to[],int max)
{
int i, j; // minor problem: j is useless
if (new_strlen(from) <= max) // should be < instead of <=
{
for(int i = 0; i != '\0'; i++) { // here you declare a new i variable
// unrelated to the i declared at the beginning
to[i] = from[i];
}
to[i+1] = '\0'; // here you use again the i declared at the beginning
// which hasn't been initialized
// and i already is the index of the terminator
// therefore it should be to[i]
}
return 0;
}
This line contains two errors:
for(int i = 0; i != '\0'; i++)
i != '\0' is equivalent to i != 0. Now youv'e probably realized your error. Actually you need to test if from[i] is 0.
to[i+1] = '\0' : here i has already been incremented by the for loop, i already contains the index of the \0 terminator, therefore it should be to[i] = '\0'
And finally in this line you use the i variable declard at the beginning o the function whose content is indeterminate as you have never assigned anything to it and it is most likely this line that causes the segmentation fault: to[i+1] = '\0';
Finally there is another problem that will cause problems if the length of the string is max:
if (new_strlen(from) <= max) // should be < instead of <=
If the length of the string is max, then \0 will be put one beyond the end of the buffer, hence a buffer overflow.
You want this:
int copyText(char from[],char to[],int max)
{
if (new_strlen(from) < max)
{
int i;
for(i = 0; from[i] != '\0'; i++)
to[i] = from[i];
}
to[i] = '\0';
}
return 0;
}
Three issues with copyText
i != '\0' should be from[i] != '\0'
int i = 0 should be just i = 0 in for loop to not shadow the other i and also pointless to do it.
to[i+1] should be just to[i]
I modify my program like you said.
My program
#include <stdio.h>
#include <stdlib.h>
int new_strlen (char *tab)
{
int i;
for (i = 0; tab[i] != '\0'; ++i);
return i;
}
int copyText(char from[],char to[],int max)
{
if (new_strlen(from) < max)
{
int i;
for(int i = 0; from[i] != '\0'; i++)
{
to[i] = from[i];
}
to[i] = '\0';
}
return 0;
}
int main (int argc, char *argv[])
{
char sentence[] = "C is \n a \n programming \t language";
char sentence2[30];
copyText(sentence, sentence2, 30);
printf("Show my array: %s \n", sentence2);
return 0;
}
The output
Show my array: h�ܙ�
Why my output is wrong?
I sloved your problem. You just missed 'form[i]' in for loop of copytext() funtion. And used (new_strlen(from) <= max) instead (new_strlen(from) < max). And removed to[i+1] = '\0'; which was not needed.
#include <stdio.h>
#include <stdlib.h>
int new_strlen (char *tab)
{
int i;
for (i = 0; tab[i] != '\0'; ++i);
return i;
}
int copyText(char from[],char to[],int max)
{
if (new_strlen(from) <= max)
{
for(int i = 0; from[i] != '\0'; i++)
{
to[i] = from[i];
}
}
return 0;
}
int main (int argc, char *argv[])
{
char sentence[] = "C is \n a \n programming \t language";
char sentence2[1000];
copyText(sentence, sentence2, 1000);
printf("Show my array: %s \n", sentence2);
return 0;
}
I have a task. I must copy all values form one char array
(sentence[]) to another empty char array sentence2[]),
I you must copy all values then the third parameter of the function copyText
int copyText(char from[],char to[],int max);
is redundant. In general it does allow to copy all values.
I think that by "all values" you mean all characters of a string stored in the source array.
To copy a string from one character array to another character array the function that calculates the length of the string is not required. It is also redundant.
The return type int of the function copyText does not make a sense. The character array from which the stored string is copied shall have the qualifier const.
Standard C string functions follow the convention that the destination character array should be the first function parameter and functions should return pointer to the destination character array.
Within the function the declared variable j is not used
int i, j;
The reason of the segmentation fault is that you are using the non-initialized variable i to set the terminating zero character in the destination array. That is you declared an uninitialized variable i
int i, j;
then in the if statement in its inner loop
if (new_strlen(from) <= max)
{
for(int i = 0; i != '\0'; i++) {
^^^^^^^^^
to[i] = from[i];
}
to[i+1] = '\0';
}
you declared one more variable i which will not be alive outside the loop. The loop itself iterates never because the condition of the loop
i != '\0'
is not satisfied. The variable i was initialized by 0 and is compared with the same 0 that is written as an octal character literal.
So in this statement
to[i+1] = '\0';
there is used the initialized variable i declared in the beginning of the function before the if statement.
I am sure what you are required to write is an analog of ths atndard C function strcpy.
In this case the program can look the following way
#include <stdio.h>
char * copyText( char to[], const char from[] )
{
for ( char *p = to; ( *p++ = *from++ ) != 0; ) { /* empty */ }
return to;
}
int main (void)
{
enum { N = 1000 };
char sentence[] = "C is \n a \n programming \t language";
char sentence2[N];
printf("Show my array: %s \n", copyText(sentence2, sentence ) );
return 0;
}
The program output is
Show my array: C is
a
programming language

Converting Hexadecimal string to int

Write a C function, that accepts a null-terminated string, containing a hexadecimal string, and returns the integer value. You cannot call any C library function, except strlen() to code the function. The decimal string will only contain 0-4 ASCII characters from ‘0’ through ‘9’ and ‘A’ through ‘F’. No error handling is required. If the string is empty, then return a value of 0.
I've constantly tried fixing my errors, but once I fix them, new errors pop up, resulting in me being confused.
#include <stdlib.h> /*used for EXIT_SUCCESS */
#include <stdio.h> /*used for printf */
#include <string.h> /* used for strlen */
#include <stdbool.h> /* used for bool */
#include <math.h>
unsigned int hexStringTouint(const char str[], int length, int n[])
{
int i, j;
int intvalue = 0;
int digit;
for(i = (length-1), j = 0; i --, j++)
{
if(n[i]>='0' && n[i] <='9')
{
digit = n[i] - 0x30;
}
else if(n[i]>= 'A' && n[i] <= 'F')
{
switch(n[i])
{
case 'A': digit = 10; break;
case 'B': digit = 11; break;
case 'C': digit = 12; break;
case 'D': digit = 13; break;
case 'E': digit = 14; break;
case 'F': digit = 15; break;
}
}
intvalue += digit*pow(16,j);
}
printf("int value is %d\n", intvalue);
return 0;
}
int main(void)
{
int i, length, intvalue;
unsigned char n[] = "";
printf("Enter your hexadecimal string: ");
scanf("%c\n", n);
intvalue = 0;
length = strlen(n);
return EXIT_SUCCESS;
}
I am getting error messages saying
expected ';' in 'for' statement specifier
and how const char* converts between pointers and integers.
Much of OP's code is the right track, yet various coding errors exist.
Add test condition
// for(i = (length-1), j = 0; i --, j++)
// v
for(i = (length-1), j = 0; i >= 0; i --, j++)
cannot call any C library function, except strlen()
// intvalue += digit*pow(16,j);
intvalue += digit*(1u << (4*j));
Return the value
Requirement "... and returns the integer value"
//int intvalue = 0;
//...
//printf("int value is %d\n", intvalue);
//return 0;
unsigned intvalue = 0;
...
printf("integer value is %u\n", intvalue);
return intvalue;
Buffer too small
// unsigned char n[] = "";
// scanf("%c\n", n);
char n[100] = "";
scanf("%99s", n);
hexStringTouint()
Function not called in main().
Other issues exist
A simpler approach
unsigned hexStringTouint2(const char *str) {
unsigned value = 0;
while (*str) {
unsigned digit = hexCharTouint(*str); // tbd code
value = value*16 + digit;
str++;
}
return value;
}

Need to make a function which returns an int based on which char argument has more uppercase letters

I'm trying to write a function which will:
return :
0 if the strings have the same number of uppercase letters (A through Z)
-1 if s1 has more uppercase letters than s2
1 if s2 has more uppercase letters than s1
My biggest issue is the fact that strings aren't treated the same way in c as other languages which I have more experience in (java, python) I'm also a bit confused on when I should reference pointers/ dereference them. Here is my code:
#include <stdio.h>
#include <string.h>
int more_caps(char * s1, char * s2);
int main(int argc, char **argv){
int result = more_caps(argv[1], argv[2]);
printf("%d %s %s", result, argv[1], argv[2]);
return 0;
}
//EVERYTHING BEFORE THIS MUST NOT BE CHANGED------
int more_caps(char * s1, char *s2){
char * s1caps = strdup(s1);
char * s2caps = strdup(s2);
int *s1counter;
int *s2counter;
int i;
for(i = 0; i < sizeof(s1caps); i++){
int val1;
val1 = (int) *s1caps[i];
if (val1 > 65 && val1 <= 90){
*s1counter += 1;
}
}
for (i = 0; i < sizeof(s2caps); i ++ ){
int val2;
val2 = (int) *s2caps[i];
if (val2 > 65 && val2 <= 90){
*s2counter += 1;
}
}
if (*s1counter > *s2counter){
printf("\n");
return -1;
}
if (*s1counter < *s2counter){
printf("\n");
return 1;
}
else {
return 0;
}
}
I'm really confused on parsing through a char object and how i need to allocate memory or something. From reading the documentation, strdup(char) allocates the exact memory + 1 byte for the character i'm putting in the function? In anycase it's either seg faults or "indirection requires pointer operand". Any help? Thanks
No need to duplicate the strings nor use of magic numbers like 65. March down each string counting the occurrences of upper case letters using isupper()
#include <ctype.h>
int more_caps(char * s1, char *s2) {
unsigned up_count1 = 0;
// while pointer is not point to the terminating null character ...
while (*s1) {
if (isupper(*s1)) up_count1++;
s1++;
}
unsigned up_count2 = 0;
while (*s2) {
if (isupper(*s2)) up_count2++;
s2++;
}
// The compare/subtraction is idiomatic in C
// Each compare returns 0 or 1
return (up_count2 > up_count1) - (up_count2 < up_count1);
}
Some pedantic improvements for your later C education:
When using an index in C, or a count of elements in an array, the type size_t is preferred as it is the right size to index any array. Type int is sometimes too narrow.
size_t up_count1 = 0;
The is...() functions take int values in the range unsigned char and EOF. Casting to unsigned char is warranted here, but I doubt your test cases will expose the weakness of a non-casted usage.
if (isupper((unsigned char) *s1)) up_count1++;
#include <stdio.h>
#include <string.h>
int more_caps(char * s1, char * s2);
int main(int argc, char **argv){
int result = more_caps(argv[1], argv[2]);
printf("%d %s %s", result, argv[1], argv[2]);
return 0;
}
int more_caps(char * s1, char *s2){
//char * s1caps = strdup(s1);
//char * s2caps = strdup(s2);
int s1counter;
int s2counter;
s1counter = 0;
s2counter = 0;
int i;
for(i = 0; s1[i] != '\0'; i++){
int val1;
val1 = (int ) s1[i];
if (val1 > 65 && val1 <= 90){
s1counter += 1;
}
}
for (i = 0; s2[i] != '\0'; i ++ ){
int val2;
val2 = (int ) s2[i];
if (val2 > 65 && val2 <= 90){
s2counter += 1;
}
}
if (s1counter > s2counter){
printf("\n");
return -1;
}
if (s1counter < s2counter){
printf("\n");
return 1;
}
else {
return 0;
}
}
The fixed function which seems to work quite well. Thank you for the help.

C - Find most frequent element in char array

i'm developing a little function to display the most frequent character in a (char) array.
This is what I've accomplished so far, but I think i'm on the wrong way.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char test[10] = "ciaociaoci";
max_caratt(test, 10);
}
int max_caratt(char input[], int size)
{
int i;
char max[300];
max[0] = input[0];
for (i=0; i<size; i++)
{
if(strncmp(input,input[i],1) == 1)
{
printf("occourrence found");
max[i] = input[i];
}
}
}
Any help?
Actually, the correct code is this.
It's just a corrected version of IntermediateHacker's below snippet.
void main()
{
int array[255] = {0}; // initialize all elements to 0
char str[] = "thequickbrownfoxjumpedoverthelazydog";
int i, max, index;
for(i = 0; str[i] != 0; i++)
{
++array[str[i]];
}
// Find the letter that was used the most
max = array[0];
index = 0;
for(i = 0; str[i] != 0; i++)
{
if( array[str[i]] > max)
{
max = array[str[i]];
index = i;
}
}
printf("The max character is: %c \n", str[index]);
}
The easiest way to find the most common character is to create an int array of 255 and just increment the arraly element that corresponds to the character. For example: if the charcter is 'A', then increment the 'A'th element (if you look at any ascii table you will see that the letter 'A' has a decimal value of 65)
int array[255] = {0}; // initialize all elements to 0
char str[] = "The quick brown fox jumped over the lazy dog.";
int i, max, index;
// Now count all the letters in the sentence
for(i = 0; str[i] != 0; i++)
{
++array[str[i]];
}
// Find the letter that was used the most
max = array[0];
index = 0;
for(i = 0; str[i] != 0; i++)
{
if( array[i] > max)
{
max = array[i];
index = i;
}
}
printf("The max character is: %c \n", (char)index);
You're passing a (almost) string and a char to strncmp(). strncmp() takes two strings (and an integer). Your program shouldn't even compile!
Suggestion: increase the warning level of your compiler and mind the warnings.
You may want to look at strchr() ...
Assuming an input array of 0-127, the following should get you the most common character in a single pass through the string. Note, if you want to worry about negative numbers, shift everything up by +127 as needed...
char mostCommonChar(char *str) {
/* we are making the assumption that the string passed in has values
* between 0 and 127.
*/
int cnt[128], max = 0;
char *idx = str;
/* clear counts */
memset((void *)cnt, 0, sizeof(int) * 128);
/* collect info */
while(*idx) {
cnt[*idx]++;
if(cnt[*idx] > cnt[max]) {
max = *idx;
}
idx++;
}
/* we know the max */
return max;
}
If you don't need to preserve the input array, you could sort the input array first, then find the longest contiguous run of a single character. This approach is slower, but uses less space.
I made a working version using structs. It works fine, I guess, but I think there's a MUCH better way to write this algorithm.
#include <stdio.h>
#include <stdlib.h>
struct alphabet {
char letter;
int times;
};
typedef struct alphabet Alphabet;
void main() {
char string[300];
gets(string);
Alphabet Alph[300];
int i=0, j=0;
while (i<=strlen(string)) {
while(j<=300) {
if(string[i] != Alph[j].letter) {
Alph[i].letter = string[i];
Alph[i].times = 1;
}
else {
Alph[j].times++;
}
j++;
}
j=0;
i++;
}
int y,max=0;
char letter_max[0];
for (y=0; y<strlen(string); y++) {
printf("Letter: %c, Times: %d \n", Alph[y].letter, Alph[y].times);
if(Alph[y].times>max) {
max=Alph[y].times;
letter_max[0]=Alph[y].letter;
}
}
printf("\n\n\t\tMost frequent letter: %c - %d times \n\n", letter_max[0], max);
}
I saw you all creating big arrays and "complex" stuff so here I have easy and simple code xD
char most_used_char (char s[]) {
int i; //array's index
int v; //auxiliary index for counting characters
char c_aux; //auxiliary character
int sum = 0; //auxiliary character's occurrence
char c_max; //most used character
int max = 0; //most used character's occurrence
for (i = 0; s[i]; i++) {
c_aux = s[i];
for (v = 0; s[v]; v++)
if (c_aux == s[v]) sum++; /* responsible cycle for counting
character occurrence */
if (sum > max) { //checks if new character is the most used
max = sum;
c_max = c_aux;
}
sum = 0; /* reset counting variable so it can counts new
characters occurrence */
}
return c_max; //this is the most used character!
}

Implementation of strspn( )

The definition of library function strspn is:
size_t strspn(const char *str, const char *chars)
/* Return number of leading characters at the beginning of the string `str`
which are all members of string `chars`. */
e.g. if str is "fecxdy" and chars is "abcdef" then the function would return 3, since f, e and c all appear somewhere in chars, giving 3 leading characters of str, and x is the first character of str which is not a member of chars.
Could someone help me write an implementation of strspn in C. The only library function I am allowed to call from the implementation is strlen?
The basic idea is to step through the string, one character at a time, and test if it's in the character set. If it's not, stop and return the answer. In pseudocode, that would look like:
count = 0
for each character c in str
if c is not in chars
break
count++
return count
The if c is not in chars test can be implemented by iterating through all of the characters of chars and testing if c matches any of the characters. Note that this is not the fastest implementation, since it involves stepping through the chars string for each character in str. A faster implementation would use a lookup table to test if c is not in chars.
I found this question while going over old exams. You weren't allowed to use indexing or any standard functions. Here's my attempt at a solution:
#include <stdio.h>
size_t myStrspn(const char *str1, const char *str2){
size_t i,j;
i=0;
while(*(str1+i)){
j=0;
while(*(str2+j)){
if(*(str1+i) == *(str2+j)){
break; //Found a match.
}
j++;
}
if(!*(str2+j)){
return i; //No match found.
}
i++;
}
return i;
}
void main(){
char s[] = "7803 Elm St.";
int n = 0;
n = myStrspn(s,"1234567890");
printf("The number length is %d. \n",n);
}
Here's the solution from the exam:
#include<stdio.h>
size_t strspn(const char* cs, const char* ct) {
size_t n;
const char* p;
for(n=0; *cs; cs++, n++) {
for(p=ct; *p && *p != *cs; p++)
;
if (!*p)
break;
}
return n;
}
For loops made it much more compact.
I think this should be pretty fast
size_t strspn(const unsigned char *str, const unsigned char *chars){
unsigned char ta[32]={0};
size_t i;
for(i=0;chars[i];++i)
ta[chars[i]>>3]|=0x1<<(chars[i]%8);
for(i=0;((ta[str[i]>>3]>>(str[i]%8))&0x1);++i);
return i;
}
Thanks to others for sanity checks.
A naive implementation of strspn() would iterate on the first string, as long as it finds the corresponding character in the second string:
#include <string.h>
size_t strspn(const char *str, const char *chars) {
size_t i = 0;
while (str[i] && strchr(chars, str[i]))
i++;
return i;
}
Given that you are not allowed to call strchr(), here is a naive native implementation:
size_t strspn(const char *str, const char *chars) {
size_t i, j;
for (i = 0; str[i] != '\0'; i++) {
for (j = 0; chars[j] != str[i]; j++) {
if (chars[j] == '\0')
return i; // char not found, return index so far
}
}
return i; // complete string matches, return length
}
Scanning the second string repeatedly can be costly. Here is an alternative that combines different methods depending on the length of chars, assuming 8-bit bytes:
size_t strspn(const char *str, const char *chars) {
size_t i = 0;
char c = chars[0];
if (c != '\0') { // if second string is empty, return 0
if (chars[1] == '\0') {
// second string has single char, use a simple loop
while (str[i] == c)
i++;
} else {
// second string has more characters, construct a bitmap
unsigned char x, bits[256 / 8] = { 0 };
for (i = 0; (x = chars[i]) != '\0'; i++)
bits[x >> 3] |= 1 << (x & 7);
// iterate while characters are found in the bitmap
for (i = 0; (x = str[i]), (bits[x >> 3] & (1 << (x & 7))); i++)
continue;
}
}
return i;
}
int my_strspn(const char *str1,const char *str2){
int i,k,counter=0;
for(i=0;str1[i]!='\0';i++){
if(counter != i) break;
for(k=0;str2[k]!='\0';k++){
if(str1[i]==str2[k])
counter++;
}
}
return counter;
}
Create a lookup table (a poor man's set) for all possible ASCII chars, and just lookup each character in str. This is worst case O(max(N,M)), where N is the number of characters in str and M is the number of characters in chars.
#include <string.h>
size_t strspn(const char *str, const char *chars) {
int i;
char ch[256] = {0};
for (i = 0; i < strlen(chars); i++) {
ch[chars[i]] = 1;
}
for (i = 0; i < strlen(str); i++) {
if (ch[str[i]] == 0) {
break;
}
}
return i;
}
This could also be solved without using strlen at all, assuming both strings are zero-terminated. The disadvantage of this solution is that one needs 256 bytes of memory for the lookup table.
Without touching a C-compiler for the last couple of years. From the top of my head something like this should work:
int spn = 0;
while(*str++ != '\0')
{
char *hay = chars;
bool match = false;
while(*hay++ != '\0')
{
if(*hay == *str)
{
match = true;
break;
}
}
if(match)
spn++;
else
return spn;
}
return spn;
Well, implementing a standard library for my OS, here is my solution (C++).
KCSTDLIB_API_FUNC(size_t DECL_CALL strspn(const char * str1, const char * str2))
{
size_t count = 0;
auto isin = [&](char c)
{
for (size_t x = 0; str2[x]; x++)
{
if (c == str2[x])
return true;
};
return false;
};
for (; isin(str1[count]); count++);
return count;
}

Resources