-4

let say I have the string " I own many pets". How can I find the length of the string before the word "many" in C?

thedude
  • 1
  • 2
  • Did you look at [similar questions](https://stackoverflow.com/search?q=[c]+find+substring)? The answers should get you at least towards a partial solution. – 5gon12eder Feb 16 '16 at 18:37
  • Possible duplicate of [How to find substring from string?](http://stackoverflow.com/questions/13195353/how-to-find-substring-from-string) – user1803551 Feb 17 '16 at 22:16

4 Answers4

2

Just find the index of the first occurence of "many"

You can use the strstr() function to do this, and just find the difference between the pointer returned by strstr() and the pointer to the whole string.

As pointed out by @4386427 this solution may not work if we talk about words (word ≠ substring).

So if you want to do something with words you will have to check if there is a space character before and after your substring (and handle the cases when the word is at the beginning or the end of the string you search the substring in).

vmonteco
  • 14,136
  • 15
  • 55
  • 86
  • can you please elaborate? – thedude Feb 16 '16 at 18:38
  • `His face is rather small` - find the length before the word `is` .... maybe `strstr`alone is not the solution – Support Ukraine Feb 16 '16 at 18:43
  • 2
    @thedude What have you tried so far and what don't you understand? – vmonteco Feb 16 '16 at 18:44
  • 1
    @4386427 It depends if we are talking about words (characters between space characters) or substrings. But then you can still do your own `findwordinstr()` function from `strstr()` if we are talking about words. But it's fine if we talk about substrings. – vmonteco Feb 16 '16 at 18:46
  • i want to replace a word in a string with another word, but that word does not have to be the same length. I can do it if they are the same length but I don't know how to do it if they are different lengths. I though of just stitching together there strings to do that. but I am not sure how to do it. – thedude Feb 16 '16 at 18:47
  • @vmonteco - the title and question clearly tells this is about a word - not about a sequence of characters. Therefore your solution doesn't work. – Support Ukraine Feb 16 '16 at 18:48
  • @Michi - I did not intend to say `strstr` could not be used for this problem. I only stated that `strstr`alone would not do it. – Support Ukraine Feb 16 '16 at 19:41
0

i want to replace a word in a string with another word, but that word does not have to be the same length. I can do it if they are the same length but I don't know how to do it if they are different lengths. I though of just stitching together there strings to do that. but I am not sure how to do it.

Finding each word in the string uses strstr(mystr, " "); Assuming that there is only one space between words (just to make the analysis simple), create a while loop using start and end. Each word begins at start and has the blank after the word in the end pointer. Set up the array of pointers using this loop

/* This assumes there is only one space between words
   It also assumes there are no leading or trailing blanks
   The assumptions are just for ease of analysis.
*/
char str[] ="This is a simple string";
char *start = str;
char *end = NULL;
int count = 0;
char mystring[MAX_STRINGS][MAX_SIZE];
while(end = strstr(start," "))
{
     len = end - start;
    // copy the substring into the array using strncpy()
    strncpy(mystring[count], start, len);
    // add the final '\0' character to the string in the array
    mystring[count++][len] = '\0';
    start = end + 1;
}
// Copy the last substring int the array
// end is now NULL but the substring ends with '\0'
// Thus a plain strcpy() is all that is required.
strcpy(mystring[count], start);

You should set up your list of words as an array of pointers. I will give this as a set of steps rather than code so that you can build the code yoursel

  1. Create an array of pointers to strings.

    char *mystrings[MAX_STRINGS];

  2. Split the large sentence string into individual words and put each word into a separate string. You can use malloc to create the appropriate sized buffer.

  3. Identify the pointer that has the word you want to replace.

  4. Create a pointer to the new word and put it into the array

  5. Free the old pointer.

  6. concatenate the strings in the array into a new string using strcat().

  7. Free the pointers and make sure that you do not overrun the final buffer when you do the strcat()

Another alternative is to create a two dimensional character array.

  char mystrings[MAX_STRINGS][MAX_SIZE];

Use a similar process, except use strcpy() to copy the words into the buffers. The replacement of the old word is also done with strcpy() and you do not have to free the old pointer. Again make the new sentence as a string using strcat(). Note that since strcpy() puts the final NUL character in place, it does not matter that the two words are different sizes as long as you do not overrun the buffer. Similarlt strcat() would put the final NUL in place to make the resultant string as long as you do not overrun the buffer.

sabbahillel
  • 4,357
  • 1
  • 19
  • 36
0

One way is to check first if the sub string is found, if found print its position -1.

Try the following:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void checkString(char *string1, char *string2);

int main(void){
    char test[256] = "I own many pets";
    char string2[] = "many";

    checkString(test, string2);
    return 0;
}

void checkString(char *string1, char *string2){
    char *s1, *s2, *s3;

    size_t lenstring1 = strlen(string1);
    size_t lenstring2 = strlen(string2);

    if (lenstring2 < 1){
        printf("There is no substring found");
        exit(1);
    }

    size_t i=0,j=0;
    int found=0;

    s1 = string1;
    s2 = string2;


    for(i = 0; i < lenstring1; i++){
        if(*s1 == *s2){
            s3 = s1;
            for(j = 0;j < lenstring2;j++){
                if(*s3 == *s2){
                  s3++;s2++;
                }else{
                    break;
                }
            }

            s2 = string2;
            if(j == strlen(string2)){
                found = 1;
                printf("The length is %zu\n", i);
              }
          }
        s1++;
    }

    if(found == 0){
        printf("No match Found");
    }
}

Output:

The length is 6
Michi
  • 5,175
  • 7
  • 33
  • 58
0
char *replace(char *str, char *old, char *new)
{
    char *ret;
    int lold, lnew;
    char *pos = strstr(str, old);

    if(pos == NULL)
       return NULL;

    lnew = strlen(new);
    lold = strlen(old);
    ret = malloc(1+strlen(str)+lnew-lold);
    if(pos != str)
        strncpy(ret, str, pos-str);
    strcat(ret, new);
    strcat(ret, pos+lold);
    return ret;
}
Bing Bang
  • 524
  • 7
  • 16