Substring Extraction exercise [closed] - c

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Given 2 strings, write a function that returns the position of String B that matches String A if String A is a substring of String B. Otherwise return -1.
Example:
strA = "ello"
strB = "Hello_World"
Your function should return 1.
strA = "blah"
strB = "blha"
Your function should return -1.

Is this homework? Anyway, look the string.h documentation and you should find what you need without much trouble. You will need to write a very thin wrapper over one of the functions. Or, of course, you can just write it all yourself.
EDIT: Well, someone else gave a answer, so here's my attempt.
#include <string.h>
ssize_t str_index(const char *strA, const char *strB)
{
const char *result;
return (result = strstr(strB, strA)) ? (result - strB) : -1;
}
The only tricks are that the parameter order is reversed from strstr, you're returning an ssize_t instead of char *, and the failure code is thus -1.

Brute force version:
int strpos(char* a, char* b) {
int n1, n2, i, j;
n1 = strlen(a);
n2 = strlen(b);
for (i = 0; i < n1-n2; i++) {
for (j = 0; j < n2; j++) {
if (a[i+j] != b[j]) break;
else if (j+1 == n2) return i;
}
}
return -1;
}
More effective algorithms: Wikipedia: String searching

#include <string.h>
int search(char* a, char* b) {
char* pos;
pos = strstr(b, a);
if(pos == 0) return -1;
return (int)(pos-b);
}

This sounds almost exactly like a homework problem. In the strange case that it is not a homework problem, the C library function strstr returns a pointer to the first occurrence of a string inside another (or null if it is not there). From there, it is trivial to determine the index using pointer arithmetic.

Trying learning about strstr. Its available in string.h
There is NEVER a reason to code something already available in the standard library.
Unless ofcourse, its a homework question :)

Related

Regarding C (not C++) does doing math in comparison statements help or hurt efficiency? What about declaring pointers? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Since people can't seem to read I'm editing the question, and debating removal. I had simplified code representing some logic I'm working on optimizing in a large and very old project. I asked them to not focus so much on the code as much as the concepts of coding in C... I had to use code to help ask question because I'm not sure how to word properly otherwise.
Regarding C (not C++) does doing math in comparison statements help or hurt efficiency? What about declaration of pointers? SORRY can't give code examples as the syntax will be nitpicked to hell before I can get an answer.
Performing comparisons between expression results or storing the values into local variables before the comparison usually does not make much of a difference, except when the computation can be avoided. Here is a classic example:
int count_char(const char *s, char c) {
int count = 0;
for (int i = 0; i < strlen(s); i++) {
if (s[i] == c)
count++;
}
return count;
}
Computing the length of the string for each iteration is very inefficient. Computing it once in the loop initial phase is better:
int count_char(const char *s, char c) {
int count = 0;
for (int i = 0, len = strlen(s); i < len; i++) {
if (s[i] == c)
count++;
}
return count;
}
Yet a different approach with pointers (as mentioned in your question) may prove even more efficient:
int count_char(const char *s, char c) {
int count = 0;
while (*s) {
if (*s++ == c)
count++;
}
return count;
}
And here is a tighter version, albeit less readable:
int count_char(const char *s, char c) {
int count = 0;
while (*s) {
count += (*s++ == c);
}
return count;
}
Note that all of the above functions should use size_t instead of int for the i, len and count variables as, on some platforms, the length of the string could be larger than the maximum value of type int.
Note also that a very good optimizing compiler could produce similar and efficient code for all versions as strlen() is a pure function and the contents of s can be determined to remain constant during the execution of the function, but it is not necessarily true for more complicated examples.

How to convert a string to an integer in C programming language, based on this strict example? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Example:
// variable fixed
Char specialstring[PATH_MAX];
int integernumber;
int xx = 1 ;
int yy = 1 ;
strncopy( specialstring, "1369", ... bla);
// here we go !! help there below please
integernumber=atoi(specialstring);
mvprintw( yy , xx , "%d" , integernumber );
Please help me in the way to convert the specialstring to an integer?
thank you
In your code, you have two mistakes:
1) strncopy is not the function you wants its strncpy. its man page:
char *strncpy(char *restrict s1, const char *restrict s2, size_t n);
Here s1 is destination string and s2 is source string , n is number of chars you wants to copy from source.
So correct:
strncopy( specialstring, "1369", ... bla);
^ ^ should be `n` num of chars you wants to
strncpy copy in `specialstring`
into
strncpy( specialstring, "1369", 4);
2) In declaration of specialstring, Char is wrong you should write small c
Char specialstring[PATH_MAX];
^ small letter
char specialstring[PATH_MAX];
3) atoi() is correct function you got to convert a string into int, if you wants to convert without atoi you can use sscanf() function like:
sscanf(specialstring,"%d", &integernumber);
View this: Working Code
You can use this to convert string to int without using atoi
int Convert(char * str)
{
int result =0;
int len=strlen(str);
for(int i=0,j=len-1;i<len;i++,j--)
{
result += ((int)str[i] - 48)*pow(10,j);
}
return result;
}

How to convert an integer to a character array using C [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I want to convert an integer number to a character array in C.
Input:
int num = 221234;
The result is equivalent to:
char arr[6];
arr[0] = '2';
arr[1] = '2';
arr[2] = '1';
arr[3] = '2';
arr[4] = '3';
arr[5] = '4';
How can I do this?
Make use of the log10 function to determine the number of digits and do like below:
char * toArray(int number)
{
int n = log10(number) + 1;
int i;
char *numberArray = calloc(n, sizeof(char));
for (i = n-1; i >= 0; --i, number /= 10)
{
numberArray[i] = (number % 10) + '0';
}
return numberArray;
}
Or the other option is sprintf(yourCharArray,"%ld", intNumber);
'sprintf' will work fine, if your first argument is a pointer to a character (a pointer to a character is an array in 'c'), you'll have to make sure you have enough space for all the digits and a terminating '\0'.
For example, If an integer uses 32 bits, it has up to 10 decimal digits.
So your code should look like:
int i;
char s[11];
...
sprintf(s,"%ld", i);
The easy way is by using sprintf. I know others have suggested itoa, but a) it isn't part of the standard library, and b) sprintf gives you formatting options that itoa doesn't.
Use itoa, as is shown here.
char buf[5];
// Convert 123 to string [buf]
itoa(123, buf, 10);
buf will be a string array as you documented. You might need to increase the size of the buffer.
You may give a shot at using itoa. Another alternative is to use sprintf.

Integer Overflow in C [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have this piece of code that I need to modify to demonstrate integer overflow vulnerability. I have never done it before and need a head start.
#include <stdio.h>
int myprintf(char* argv){
printf("%s\n", argv);
return 0;
}
int myprintf2(char* argv){
printf("hello world\n");
return 0;
}
int main(int argc, char** argv){
struct foodata{
int (*fptr)(char*);
int buf[4];
} foo;
foo.buf[0] = 0xdeadbeef;
foo.fptr = myprintf;
foo.buf[0xffffffff] = myprintf2;
foo.fptr(argv[1]);
return 0;
}
Ok. So your code, at least on some 32-bit platforms, does print hello world\n and not the argument from the user. We have changed the function pointer by manipulating other array. Now we want to use it for malicious purpose.
First thing - we replace myprintf2 with something dangerous, when called without some checking, like:
void set_authorized(void) {
authorized = 1;
}
Now, we need to have to get some input from user. For example we will read four numbers and use their sum as index to buf, when the input seems valid.
int a, b, c, d;
do {
scanf("%d%d%d%d", &a, &b, &c, &d);
} while (a < 0 || b < 0 || c < 0 || a + b + c > 4);
buf[a+b+c] = d;
Looks like we could never write outside the array, right?
No, the attacker can use data
a = INT_MAX;
b = 1;
c = INT_MAX;
d = (int)set_authorized
INT_MAX + 1 + INT_MAX = INT_MIN + INT_MAX = -1 (0xffffffff). So we basically have behavior like in your example, but this time it grants unprivileged user some rights.
Note:
To have this example working on 64-bit platform replace int buf[4]; with long buf[4] and 0xffffffff with 0xffffffffffffffff.

Can't find a bug here... C code [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
In this code I tried to write a function which returns 0 value if the two strings don't match, and a length of matching characters if i can find a substring in str that wholey resambles patt.
#include....
int check(char *str, char *patt, int *b)
{
if (*str == *patt && *patt != 0)
return *b * (1 + check(str+1,patt+1,&b));
else if (*patt == 0)
return 0;
else{
*b = 0;
return 0;
}
}
main()
{
char s1[SIZE] = "mama";
char s2[SIZE] = "mama";
int b = 1;
printf("%d\n",check(s1,s2,&b));
b = 1;
system ("pause");
return;
}
Here I should get the output 4, but I get -77779463.
Thanks for help!
PS I used recursion and set the b parameter as changable.
b is already a pointer to an int, so you want to make the recursive call with b and not &b.
Any decent compiler, with warnings enabled, would have alerted you to that mistake!
return *b * (1 + check(str+1,patt+1,&b));
^ dont pass address.
Pass b to it instead.

Resources