Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a char* formatted like:
* SEARCH 1 2 3 ...
with a variable number of integers separated by spaces. I would like to write a function to return an int[] with the integers after * SEARCH.
How should I go about writing this function?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int *f(const char *s, int *n /* out */){
if(strncmp(s, "* SEARCH", 8)!=0){
fprintf(stderr, "format error!\n");
*n = 0;
return NULL;
}
s += 8;
const char *p = s;
int v, len, status;
int count = 0;
while((status=sscanf(p, "%d%n", &v, &len))==1){
++count;
p +=len;
}
if(status==0){
fprintf(stderr, "format error!\n");
*n = 0;
return NULL;
}
int *ret = malloc(count * sizeof(*ret));
p = s;
count = 0;
while(EOF!=sscanf(p, "%d%n", &v, &len)){
ret[count++]=v;
p +=len;
}
*n = count;
return ret;
}
int main (void){
int i, n, *nums = f("* SEARCH 1 2 3", &n);
for(i=0; i<n; ++i)
printf("%d ", nums[i]);
printf("\n");
free(nums);
return 0;
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
TASK: // target - starting an argument in which to record results
target should be a "source" left supplemented with "fill_char" to length "cnt". If cnt is less than the length of the source, it becomes equal to the target source.
// Now is moving on right and must to change something but I'm not sure what and how. Can you give me advice. And if you have some different decision please share with me. Thank you :)))!
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <batch_util.h>
int lpad(char* target, char* source, char fill_char, int cnt)
{
int i;
int source_size = strlen(source);
for (i = 0; i < source_size; i++)
target[i] = source[i];
for (i = source_size; i < cnt; i++)
target[i] = fill_char;
target[i] = '\0';
return 0;
}
int main(int argc, char* argv[])
{
char source[128];
char target[128];
char fill_char;
int cnt;
scanf("%s\n", &source);
scanf("%c\n", &fill_char);
scanf("%d\n", &cnt);
lpad(target, source, fill_char, cnt);
printf("%s\n", target);
return 0;
}
For starters you can use standard C string functions instead of loops.
It seems you mean the following
#include <stdio.h>
#include <string.h>
char * lpad( char *target, const char *source, char fill_char, size_t cnt )
{
size_t source_size = strlen( source );
if ( source_size < cnt )
{
memset( target, fill_char, cnt - source_size );
}
strcpy( target + ( source_size < cnt ? cnt - source_size : 0 ), source );
return target;
}
#define N 16
int main(void)
{
char *source= "monkey";
char target[N];
puts( lpad( target, source, '*', N - 1 ) );
return 0;
}
The program output is
*********monkey
As for your code then the function does not append anything to the left.
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 6 years ago.
Improve this question
How can I compare 2 strings with maximum length 100 and print the equal part of them, like:
STRING 1 : ABCDEFGHIJKLMNOP
STRING 2 : QWERABCDZXVBERTY
The equal parts of these strings are : ABCD
Please look if this program can help you. It takes the two strings as arguments from the command line.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int *substring(char *s, char *t) {
int strlen1 = strlen(s);
int strlen2 = strlen(t);
int len = strlen1 < strlen2 ? strlen1 : strlen2;
int i, j, k;
int longest = 0;
int **ptr = (int **) malloc(2 * sizeof(int *));
static int *ret;
ret = (int *) calloc(strlen1 + 1, sizeof(int));
for (i = 0; i < 2; i++)
ptr[i] = (int *) calloc(strlen2, sizeof(int));
k = 0;
for (i = 0; i < strlen1; i++) {
memcpy(ptr[0], ptr[1], strlen2 * sizeof(int));
for (j = 0; j < strlen2; j++) {
if (s[i] == t[j]) {
if (i == 0 || j == 0) {
ptr[1][j] = 1;
} else {
ptr[1][j] = ptr[0][j - 1] + 1;
}
if (ptr[1][j] > longest) {
longest = ptr[1][j];
k = 0;
ret[k++] = longest;
}
if (ptr[1][j] == longest) {
ret[k++] = i;
ret[k] = -1;
}
} else {
ptr[1][j] = 0;
}
}
}
for (i = 0; i < 2; i++)
free(ptr[i]);
free(ptr);
ret[0] = longest;
return ret;
}
int main(int argc, char *argv[]) {
int i, longest, *ret;
if (argc != 3) {
printf("usage: longest-common-substring string1 string2\n");
exit(1);
}
ret = substring(argv[1], argv[2]);
if ((longest = ret[0]) == 0) {
printf("There is no common substring\n");
exit(2);
}
i = 0;
while (ret[++i] != -1) {
printf("%.*s\n", longest, &argv[1][ret[i] - longest + 1]);
}
exit(0);
}
Test
./a.out ABCDEFGHIJKLMNOP QWERABCDZXVBERTY
ABCD
Compare two strings is a common skill which is very easy to find information. First you should read string.h library where you can find a lot of useful function in order to work with strings.
Then the first stupid algorithm is to compare each char of first string with the second and if it matches you add that char to the result.
But it would be smarter to order the two strings and then compare them, saving many comparisons.
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 6 years ago.
Improve this question
I got string containing numbers separated by spaces. Numbers can be single-digit, two-digit, or perhaps more-digit. Check the example.
"* SEARCH 2 4 5 12 34 123 207"
I don't know how long the string is (how many numbers it contains), so I cant initiate the array properly. The result should look like this:
array = {2,4,5,12,34,123,207}
Do you have any ideas how to perform this?
like this:
#include <stdio.h>
#include <stdlib.h>
int main(void){
char *input = "* SEARCH 2 4 5 12 34 123 207";
int len = 0;
sscanf(input, "%*[^0-9]%n", &len);//count not-digits(The Number isn't negative)
char *p = input + len;
char *start = p;
int v, n = 0;
while(1 == sscanf(p, "%d%n", &v, &len)){
++n;//count elements
p += len;
}
int array[n];//or allocate by malloc(and free)
char *endp = NULL;
int i;
for(i = 0; i < n; ++i){
array[i] = strtol(start, &endp, 10);
start = endp + 1;
}
//check print
for(i = 0; i < n; ++i)
printf("%d ", array[i]);
puts("");
return 0;
}
You can try this approach. It uses a temporary buffer to hold the current integer that is being processed. It also uses dynamic arrays, to deal with different lengths of the string you want to process, and expands them when necessary. Although using strtok Would be better in this situation.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int
main(int argc, char *argv[]) {
char message[] = "* SEARCH 2 4 5 12 34 123 207";
char *buffer = NULL;
int *integers = NULL;
int buff_size = 1, buff_len = 0;
int int_size = 1, int_len = 0;
int ch, messlen, i, first_int = 0;
/* creating space for dynamic arrays */
buffer = malloc((buff_size+1) * sizeof(*buffer));
integers = malloc(int_size * sizeof(*integers));
/* Checking if mallocs were successful */
if (buffer == NULL || integers == NULL) {
fprintf(stderr, "Malloc problem, please check\n");
exit(EXIT_FAILURE);
}
messlen = strlen(message);
/* going over each character in string */
for (ch = 0; ch < messlen; ch++) {
/* checking for first digit that is read */
if (isdigit(message[ch])) {
first_int = 1;
/* found, but is there space available? */
if (buff_size == buff_len) {
buff_size++;
buffer = realloc(buffer, (2*buff_size) * sizeof(*buffer));
}
buffer[buff_len++] = message[ch];
buffer[buff_len] = '\0';
}
/* checking for first space after first integer read */
if (isspace(message[ch]) && first_int == 1) {
if (int_size == int_len) {
int_size++;
integers = realloc(integers, (2*int_size) * sizeof(*integers));
}
integers[int_len] = atoi(buffer);
int_len++;
/* reset for next integer */
buff_size = 1;
buff_len = 0;
first_int = 0;
}
/* for last integer found */
if (isdigit(message[ch]) && ch == messlen-1) {
integers[int_len] = atoi(buffer);
int_len++;
}
}
printf("Your string: %s\n", message);
printf("\nYour integer array:\n");
for (i = 0; i < int_len; i++) {
printf("%d ", integers[i]);
}
/* Being careful and always free at the end */
/* Always a good idea */
free(integers);
free(buffer);
return 0;
}
You can read each character and verify if it is in range of >=48(Ascii of 0) and less than = 57(Ascii of 9). If so is the case read them into a array Otherwise you could copy them to a temporary string and convert to int using functions like atoi()
#include <stdio.h>
int main(int argc, char *argv[])
{
int j=0,k,res;
char buff[10];
while(str[j])
{
if((str[j]>='0')&&(str[j]<='9'))
{
k=0;
while((str[j]!=' ')&&(str[j]!='\0'))
{
buff[k]=str[j++];
k++;
}
buff[k]=0;
res=atoi(buff);
//Store this result to an array
}
j++;
}
return 0;
}
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 6 years ago.
Improve this question
I have str:
char *str = "lala";
Now, I would like convert any chars in str to hexadecimal, example:
str = convert(str);
print str: 0x6C 0x61 0x6C 0x61
^ l ^ a ^ l ^ a
How I can do that ?
char *convert(char const *str) {
int len = strlen(str);
char *retVal = (char *)malloc(5 * len);
char *pos = retVal;
int i;
for(i = 0; i < len; ++i, pos += 5) sprintf(pos, i? " 0x%x" : "0x%x", str[i]);
retVal[5 * len - 1] = '\0';
return retVal;
}
Might have missed something, haven't used C for eight years.
Simply by asking printf to do it :
void convert(char* str, size_t length) {
size_t i;
for(i = 0; i < length; i++)
printf("0x%02x ", str[i]);
}
You can achieve it by using this implementation....
#define MAX 100
char *convert(char *str)
{
char *hexStr = (char *)malloc(strnlen(str, MAX) * 5);
if (hexStr == NULL)
return NULL;
int i,j;
for (i=0, j=0; str[i]; j+=5, i++)
sprintf(hexStr + j, "0x%02x ", str[i]);
hexStr[--j] = '\0';
return hexStr;
}
char* x = str - 1;
while(*++x) printf("%02x ", (int) *x); // Print one character in hex
printf("\n") // Finish with a carriage return
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Can anyone give me a complete example of how to generate an Alphanumeric String randomly
like (ARG534UJ6) using C ? I'm completely new to C.
void gen_random(char *s, const int len) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
This is not working.
As pointed out by #IngoLeonhardt, use % (sizeof(alphanum) - 1) instead of % sizeof(alphanum)
My guess is that you don't have room for your string, try:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void gen_random(char *s, const int len) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
int main(void)
{
char *str = malloc(8 + 1);
/* initialize random seed: */
srand(time(NULL));
gen_random(str, 8);
printf("%s\n", str);
free(str);
return 0;
}