1

I have a char array that contains some string for example

char* arr = "ABCDEFGHIJKL ZMN OPQOSJFS"

and the string

char* string = "ZMN"

Is there any printing method that will print the content of arr only after the first occurrence of string in it? In this case it will print " OPQOSJFS"

What about sprintf, and if so, how do I do that?

3 Answers 3

4

sprintf won't help you here; use strstr to find the occurence and then print the source string from there on:

// note: your string constants should be of type 'const char*'
const char* haystack = "ABCDEFGHIJKL ZMN OPQOSJFS";
const char* needle = "ZMN";

// find occurence of the string
const char* out = strstr(haystack, needle);
if(out != NULL) {
    // print string, starting from the end of the occurence
    out += strlen(needle);
    printf("The string is: %s", out);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Why do you drop const for out? That makes no sense.
3

Firstly, let me tell you,

I have a char array that contains some string for example

char* arr = "ABCDEFGHIJKL ZMN OPQOSJFS"

is wrong. "ABCDEFGHIJKL ZMN OPQOSJFS" is a string literal, and arr is just a pointer, not an array.

If you indeed need arr to be called an array, you need to write it like

 char arr[] = "ABCDEFGHIJKL ZMN OPQOSJFS";

Now, for your requirement, you can have a look at strstr() function, prototyped in string.h header.

Prototype:

char *strstr(const char *haystack, const char *needle);

Description:

The strstr() function finds the first occurrence of the substring needle in the string haystack.

So, if it returns a non-NULL pointer, you can use that value to point out the location of the substring, and using index, you can get the required part of the source string.

Comments

2

strstr will give you a pointer on the substring you are looking for. You can then jump after this string and printf its content.

char * sub = strstr(arr, string);
sub += strlen(string);
printf("%s\n", sub);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.