Compare 2 strings in C and print equal part [closed] - c

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.

Related

Detect the shortest word in a sentence in C [closed]

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 2 years ago.
Improve this question
I have created the below program to detect the shortest word in a sentence for me. However, the result is not what I expected. I went through the code a few times and I still could not find the problem.
I would be very grateful if someone could lend me some help.
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
ssize_t find_short(const char *s);
int main(void)
{
char s[100] ="lets talk about C the best language";
printf("%zu", find_short(s));
}
ssize_t find_short(const char *s)
{
int n = strlen(s);
int smallest = n;
int counter = 0;
for (int i = 0; i <= n; i++)
{
if (s[i] == ' ' || s[i] == '\0')
{
if (counter <= smallest)
{
smallest = (ssize_t) counter;
counter = 0;
}
}
else
counter ++;
}
return smallest;
}
Thank you very much.
You reset counter only when counter is smallest than smallest. If a new word is shorter than any previous, it will be ignored.
ssize_t find_short(const char *s)
{
int n = strlen(s);
int smallest = n;
int counter = 0;
for (int i = 0; i <= n; i++)
{
if (s[i] == ' ' || s[i] == '\0')
{
if (counter <= smallest)
{
smallest = (ssize_t) counter;
// <-- not here
}
counter = 0; // < -- here
}
else
counter ++;
}
return smallest;
}
counter=0 should be outside the if statement
ssize_t find_short(const char *s)
{
int n = strlen(s);
int smallest = n;
int counter = 0;
for (int i = 0; i <= n; i++)
{
if (s[i] == ' ' || s[i] == '\0')
{
if (counter <= smallest)
{
smallest = (ssize_t) counter;
}
counter = 0;
}
else
counter ++;
}
return smallest;
}

How to Assign Random String to 2D Array

The program reads a file which includes one word in every line.After reading random word put random word in a pointer and return the pointer .in main function
printf("%s",func("example.txt",str)) it prints different string when the program run.I want to do this in 2d array(20*20) like table,but i could not imagine how to do this.When i print the the function in internal loop,it give me the same word in every loop step.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char *word(char *file, char *str);
int main() {
char *str ;
int i, j;
str = (char *)malloc(20);
srand(time(NULL));
char *puzzle[20][20];
for (i = 0; i < 20; i++) {
for (j = 0; j < 20; j++) {
puzzle[i][j] = word("words.txt", str);
}
}
for (i = 0; i < 20; i++) {
for (j = 0; j < 20; j++) {
printf("%s ", puzzle[i][j]);
}
printf("\n");
}
}
char *word(char *file, char *str) {
int end, loop, line;
FILE *fd = fopen(file, "r");
if (fd == NULL) {
printf("Failed to open file\n");
return (NULL);
}
srand(time(NULL));
line = rand() % 100 + 1;
for (end = loop = 0; loop < line; ++loop) {
if (0 == fgets(str, 20, fd)) {
end = 1;
break;
}
}
if (!end)
return (char *)str;
fclose(fd);
free(str);
}
I do not have your words.txt file, so I've created some random strings below.
And a note:
Because your nested loop is in the main, your code opens the file in the sub function and returns w/o closing it; then returns to the sub and reopens, and again, and again... It's always better to read at once and close the file before returning from the sub.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char **word(int countString, int maxChars) {
int i;
int j;
int k;
// allocate memory for pointers that are pointing to each string
char **arrStr = malloc(countString * sizeof(char *));
// srand(time(NULL));
for (i = 0; i < countString; i++) {
// create a random string with a length of 'k'
// say, 5 <= k <= maxChars
// that (+ 1) is for the string terminating character '\0'
k = (rand() % (maxChars - 5)) + 5 + 1;
// allocate memory for string
arrStr[i] = malloc(k * sizeof(char));
for (j = 0; j < k - 1; j++) {
*(arrStr[i] + j) = rand() % 26 + 'A';
}
*(arrStr[i] + j) = '\0';
}
return arrStr;
}
int main() {
int countString = 10;
int maxChars = 20;
char **arrStr = NULL;
int i;
arrStr = word(countString, maxChars);
for (i = 0; i < 10; i++) {
printf("%s\n", *(arrStr + i));
}
// do not forget to free the strings
// and then the string pointers (array)
return 0;
}

How to order split command line arguments in lexicographical order using a function?

I'm working on a program that takes command line arguments and splits them in half and then orders them in lexicographical order.
For example:
hello, world!
would turn into:
he
ld!
llo
wor
I have a main method that reads through the arguments, a function that splits the arguments, and finally a function that is supposed to order the halves in lexicographical order. I can't get this to run properly because of argument type errors in the lexicographicalSort method and an incompatible pointer type in the main method. I'm having issues to correct these syntax errors, how exactly would I correct them? Also, is there anything here that would cause logical errors? This is what I have so far:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int splitString(char arg[], int n)
{
int len = strlen(arg);
int len1 = len/2;
int len2 = len - len1; // Compensate for possible odd length
char *s1 = malloc(len1 + 1); // one for the null terminator
memcpy(s1, arg, len1);
s1[len1] = '\0';
char *s2 = malloc(len2 + 1); // one for the null terminator
memcpy(s2, arg + len1, len2);
s2[len2] = '\0';
printf("%s\n", s1);
printf("%s\n", s2);
free(s1);
free(s2);
return 0;
}
int lexicographicalSort(char *arg[], int n)
{
char temp[50];
for(int i = 0; i < n; ++i)
scanf("%s[^\n]",arg[i]);
for(int i = 0; i < n - 1; ++i)
for(int j = i + 1; j < n ; ++j)
{
if(strcmp(arg[i], arg[j]) > 0)
{
strcpy(temp, arg[i]);
strcpy(arg[i], arg[j]);
strcpy(arg[j], temp);
}
}
for(int i = 0; i < n; ++i)
{
puts(arg[i]);
}
return 0;
}
int main(int argc, char *argv[])
{
if (argc > 1)
{
for (int i = 1; i < argc; i++)
{
int j = 1;
int k = strlen(argv[i]);
splitString(argv[i], j);
lexicographicalSort(argv[i], j);
}
}
}
Basic scheme is simple. Make an array of tuples {start_pointer, length}. Do some programming on args to split the args. Fill in the array as appropriate. Make sorting with qsort, or any other sort of your choise.
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
char *s = "hello, world! . hello.....";
char *pc;
int i, n, nargs;
struct pp{
char *p;
int l;
};
struct pp args[10], hargs[20];
struct pp *pargs;
int cmp(const void * v0, const void * v1) {
struct pp *pv0 = v0, *pv1 = v1;
return strncmp(pv0->p, pv1->p, pv0->l);
}
int main(void)
{
for(pc = s, i = 0; *pc; ++i){
sscanf(pc, "%*[^ ]%n", &n);
if(n > 0){
args[i].p = pc;
args[i].l = n;
}
for(pc += n, n = 0; isspace(*pc); ++pc);
}
for(nargs = i, i = 0; i < nargs; ++i)
printf("%d arg is: %.*s\n", i, args[i].l, args[i].p);
putchar('\n');
for(i = 0, pargs = hargs; i < nargs; ++i){
if(args[i].l == 1){
pargs->p = args[i].p;
pargs->l = 1;
pargs = pargs + 1;
}else {
pargs->p = args[i].p;
pargs->l = args[i].l / 2;
pargs = pargs + 1;
pargs->p = args[i].p + args[i].l / 2;
pargs->l = args[i].l - args[i].l / 2;
pargs = pargs + 1;
}
}
putchar('\n');
for(nargs = pargs - hargs, i = 0; i < nargs; ++i)
printf("%d arg is: %.*s\n", i, hargs[i].l, hargs[i].p);
qsort(hargs, nargs, sizeof(struct pp), cmp);
putchar('\n');
for(i = 0; i < nargs; ++i)
printf("%d arg is: %.*s\n", i, hargs[i].l, hargs[i].p);
return 0;
}
https://rextester.com/GSH22767
Upon splitting a C string, one needs one extra char to store extra null-terminator. There is one answer that bypasses this by storing the length. For completeness, this is closer to your original intention: allocating enough space to copy the programmes arguments. It probably works slower, but one is free to use the strings elsewhere in the programme.
#include <stdlib.h> /* malloc free EXIT qsort */
#include <stdio.h> /* fprintf */
#include <string.h> /* strlen memcpy */
#include <errno.h> /* errno */
static int strcompare(const void *a, const void *b) {
const char *a_str = *(const char *const*)a, *b_str = *(const char *const*)b;
return strcmp(a_str, b_str);
}
int main(int argc, char **argv) {
char *spacev = 0, **listv = 0;
size_t spacec = 0, listc = 0;
int is_done = 0;
do { /* "Try." */
int i;
char *sv;
size_t j;
/* This requires argc > 1. */
if(argc <= 1) { errno = EDOM; break; }
/* Allocate maximum space. */
for(i = 1; i < argc; i++) spacec += strlen(argv[i]) + 2;
if(!(spacev = malloc(spacec)) || !(listv = malloc(argc * 2))) break;
sv = spacev;
/* Copy and split the arguments. */
for(i = 1; i < argc; i++) {
const char *const word = argv[i];
const size_t word_len = strlen(word),
w0_len = word_len / 2, w1_len = word_len - w0_len;
if(w0_len) {
listv[listc++] = sv;
memcpy(sv, word, w0_len);
sv += w0_len;
*(sv++) = '\0';
}
if(w1_len) {
listv[listc++] = sv;
memcpy(sv, word + w0_len, w1_len);
sv += w1_len;
*(sv++) = '\0';
}
}
/* Sort. */
qsort(listv, listc, sizeof listv, &strcompare);
for(j = 0; j < listc; j++) printf("%s\n", listv[j]);
is_done = 1;
} while(0); if(!is_done) {
perror("split");
} {
free(spacev);
free(listv);
}
return is_done ? EXIT_SUCCESS : EXIT_FAILURE;
}
It is simpler than your original; instead of allocating each string individually, it counts the maximum number of chars needed (plus two for two null terminators) and allocates the block all at once (space.) The pointers to the new list also need allocating, the maximum is 2 * argc. Once you copy and modify the argument list, one has an actual array of strings that one can qsort.

Split string into INT array in c [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 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;
}

Print out the longest substring in c

Suppose that we have a string "11222222345646". So how to print out subsequence 222222 in C.
I have a function here, but I think something incorrect. Can someone correct it for me?
int *longestsubstring(int a[], int n, int *length)
{
int location = 0;
length = 0;
int i, j;
for (i = 0, j = 0; i <= n-1, j < i; i++, j++)
{
if (a[i] != a[j])
{
if (i - j >= *length)
{
*length = i - j;
location = j;
}
j = i;
}
}
return &a[location];
}
Sorry,I don't really understand your question.
I just have a little code,and it can print the longest sub string,hope it can help.
/*breif : print the longest sub string*/
void printLongestSubString(const char * str,int length)
{
if(length <= 0)
return;
int i ;
int num1 = 0,num2 = 0;
int location = 0;
for(i = 0; i< length - 1; ++i)
{
if(str[i] == str[i+1])
++num2;//count the sub string ,may be not the longest,but we should try.
else
{
if(num2 >num1)//I use num1 store the sum longest of current sub string.
{ num1 = num2;location = i - num2;}
else
;//do nothing for short sub string.
num2 = 0;
}
}
for(i = location;str[i]== str[num1];++i)
printf("%c",str[i]);
printf("\n");
}
int main()
{
char * str = "1122222234566";
printLongestSubString(str,13);
return 0;
}
From your code it appears you want to return the longest sub-sequence (sub-string). Since I'm relearning C I thought I would give it a shot.
I've used strndup to extract the substring. I'm not sure how portable it is but I found an implementation if needed, just click on the link. It will allocate memory to store the new cstring so you have to remember to free the memory once finished with the substring. Following your argument list, the length of the sub-string is returned as the third argument of the extraction routine.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *extract_longest_subsequence(const char *str, size_t str_len, size_t *longest_len);
int main()
{
char str[] = "11222234555555564666666";
size_t substr_len = 0;
char *substr = extract_longest_subsequence(str, sizeof(str), &substr_len);
if (!substr)
{
printf("Error: NULL sub-string returned\n");
return 1;
}
printf("original string: %s, length: %zu\n", str, sizeof(str)-1);
printf("Longest sub-string: %s, length: %zu\n", substr, substr_len);
/* Have to remember to free the memory allocated by strndup */
free(substr);
return 0;
}
char *extract_longest_subsequence(const char *str, size_t str_len, size_t *longest_len)
{
if (str == NULL || str_len < 1 || longest_len == NULL)
return NULL;
size_t longest_start = 0;
*longest_len = 0;
size_t curr_len = 1;
size_t i = 0;
for (i = 1; i < str_len; ++i)
{
if (str[i-1] == str[i])
{
++curr_len;
}
else
{
if (curr_len > *longest_len)
{
longest_start = i - curr_len;
*longest_len = curr_len;
}
curr_len = 1;
}
}
/* strndup allocates memory for storing the substring */
return strndup(str + longest_start, *longest_len);
}
It looks like in your loop that j is supposed to be storing where the current "substring" starts, and i is the index of the character that you are currently looking at. In that case, you want to change
for (i = 0, j = 0; i <= n-1, j < i; i++, j++)
to
for (i = 0, j = 0; i <= n-1; i++)
That way, you are using i to store which character you're looking at, and the j = i line will "reset" which string of characters you are checking the length of.
Also, a few other things:
1) length = 0 should be *length = 0. You probably don't actually want to set the pointer to point to address 0x0.
2) That last line would return where your "largest substring" starts, but it doesn't truncate where the characters start to change (i.e. the resulting string isn't necessarily *length long). It can be intentional depending on use case, but figured I'd mention it in case it saves some grief.

Resources