Search/print specific elements in array - c

Anyone know how to search (with luck) for specific elements in an array? I'v tried about everything - except the correct way.
My two corresponding char-arrays looks something like this:
char array1[10][10]={"Alpha","Bravo","Charlie","Delta","Alpha2"}; //room for some more here
char array2[10][10]={"123456","234567","345678","456789","567890"}; //room for some more here
I can print them all by the regular for-loop:
for (i=0;i<10;i++){
printf("%s %s \n", &array1[i], &array2[i]);
}
But let's say I want do the same loop, and only print the two elements starting with 'A' (the first and last one). I thought something like this would work
do {
for (i=0;i<10;i++){
printf("Name: %s\nDate: %s\n\n", &array1[i][x], &array2[i]);
}
} while (x=='A');
That's the same for-loop, except I put the extra [x] behind &array1 to tell my 'x' have to match the first character in each element of array1 (like it will only do the for loop while (x=='A') - which is the first letter in the elements I want.
But it doesn't do any good..
Anyone have a better solution? I've tried other variants of the for loop also, without luck. I'm just stuck now...

#include <stdio.h>
int main(void) {
char array1[10][10]={"Alpha","Bravo","Charlie","Delta","Alpha2"}; //room for some more here
char array2[10][10]={"123456","234567","345678","456789","567890"}; //room for some more here
int i;
for (i=0;i<10;i++){
if(array1[i][0]=='A') //add this statement in your code
printf("%s %s \n", &array1[i], &array2[i]);
}
return 0;
}

using while you are checking x=='A' it will compare with the ASCII value of A. The condition is wrong.
you can use
while((strncmp(array,"A",1)) == 0)
this will check the first character of the string.

except I put the extra [x] behind &array1 to tell my 'x' have to match the first character in each element of array1
That's not quite how array subscripts work. As you have found, array1[i] will refer to the ith string in array1. You can then access the xth character in array1[i] by indexing into the string, i.e. array1[i][x].
You don't actually assign x anywhere, so you'll end up with undefined behaviour. What you want to do is extract the first character of array1[i] (i.e. element zero), so the following is possible:
char x = '\0';
do {
for (i=0;i<10;i++){
x = array1[i][0];
printf("Name: %s\nDate: %s\n\n", &array1[i][x], &array2[i]);
}
} while (x=='A');
You'll then notice that this probably doesn't give the behaviour you want. It'll loop over all 10 strings, then perform the x == 'A' check. You should move that inside the loop instead, e.g.
char x = '\0';
for(i = 0; i < 10; i++)
{
x = array1[i][0];
if(x == 'A')
printf("%s %s \n", &array1[i], &array2[i]);
}

Related

Couldn't understand the output of the program

#include <stdio.h>
#include<string.h>
int main(void)
{
int n,u = 0;
printf("Enter length of word ");
scanf("%d",&n);
char word[n*2];
printf("Enter the String \n");
scanf("%s", word);
printf("string that u have entered: %s\n",word);
int i = n - 1, j = n;
while(i >= 0)
{
printf("word[i-1] %c\n",word[i]);
word[j] = word[i];
printf("i %d\n",i);
printf("j %d\n",j);
i--;
j++;
}
printf("reversed word stored at the last in the same array - %s\n",word);
}
when we give the length 3 the output doesn't give any garbage value in output but when I give greater than 3 its starts to give garbage value in the output. (yeah I know we have to add '\0' at the end of the array to stop but for length 3 without that, it works.)
Here, you have declared the word as char array and alloted the size of array. So,when you are printing via indexing of array as %c --it gives the correct result. But,at the end,when you try to print the whole 'word' char array, you used %s . Now, what %s does is : when you indicate to a string, it stores the address of the first element and keep printing the value stored in those addresses in sequential manner untill it finds the null value. So,you better use a loop to print values stored in 'word' array using %c or you can convert your char array 'word' into string & then use %s to print values inside 'word'.

How to delete a string from an array of string in c

I have a multidimensional array in which I put words inside. After, I ask the user to delete a word. But it won't delete.
#include<stdio.h>
void main ()
{
int i ;
int nbr ;
char n[50][50];
char d[50];
printf("Enter the number of word you want : \n");
scanf("%d",&nbr);
for(i=0; i < nbr ; i++)
{
printf("Enter words : \n");
scanf("%s",&n[i]);
}
printf("you have enter: \n");
for(i = 0; i < nbr ; i++)
{
printf("%s \n",n[i]);
}
printf("Which word you want to remove : ? \n");
scanf("%s",&d);
for(i=0; i < nbr ; i++)
{
if(strcmp(n[i],d)==0)
{
n[i] = n[i+1] ;
i-- ;
}
}
printf("The rest of array is : \n");
scanf("%s",&n[i]);
}
[Error] assignment to expression with array type
Although arrays are implemented with pointers in C, the compiler will treat them the differently. As you can see in your own example the line n[i] = n[i+1] causes the error you see, because n[i] is an array of chars.
Even if you could make the assignment you wanted, the logic of your program still has an error. If you were able to succeed in your call to n[i] = n[i+1] you would effectively be duplicating whatever was in n[i+1] twice.
Instead you likely want to copy n[i+1] into n[i], then copy n[i+2] into n[i+1] and so on. This will be expensive, you may want to look into using a linked list instead, although this really depends on what else you want to do with this data structure.
[Error] assignment to expression with array type
In C an array can not be assigned.
You need to copy the content of the source array are into the destination array.
For the special case of a 0-terminated chararray (aka C-string) you can use the strcpy() function to do so:
strcpy(n[i], n[i+1]);

C: Function not returning full string

I'm not sure if I'm just being really dumb but this function I have made should take chars from one array and selectively put them in another to remove things like spaces and punctuation. However, what returns seems to just be the first char (from the printf).
char * getWord(char *array) {
char *temp = malloc(sizeof(char) * 20);
int i= 0;
while(i < 20) {
if(validChar(array[i])) {
printf("pass 1 - %c\n", array[i]);
temp[i] = array[i];
printf("pass 2 - %c\n", temp[i]);
i=i+1;
}
else {
i=i+1;
}
}
printf("%s\n", temp);
return temp;
}
The validChar function:
bool validChar(char given) {
char a[]=". ,;:*!?'-\n\r";
for(int q = 0; q <=12; q++) {
if(given == a[q]){
return false;
}
}
return true;
}
In each "pass 2", the correct print is shown so the loop is working as intended. The thing I really don't understand is when I remove the conditional to select valid chars, the final print statment works as intended and prints the entire string.
First, you're using just one counter for both strings in getWord. You have to separate the reading of the string with i of the writting of the temp string with another counter, say j. j will only be incremented when you actually add some character to temp.
Finally, you're missing the ending '\0' of temp before the printf in getWord.
You need two counters one for each array. Counter i, which you already use for array, and a new one j which will be used for temp.
if(validChar(array[i])) {
printf("pass 1 - %c\n", array[i]);
temp[j] = array[i];
printf("pass 2 - %c\n", temp[j]);
i=i+1;
j=j+1;
}
else {
i=i+1;
}
The reason you only printed the first character is that the memory you got from malloc happened to contain bytes set to zero. The first character that got skipped in temp, contained a zero byte, since a string is zero terminated, that is all you printed out.
Technically those zero bytes were not initialized so the behavior of your code is undefined.
The code also doesn't zero terminate the string temp, after the copying is completed. Add an assignment of '\0' to temp at position j after the while loop, and change the while loop condition from 20 to 19 (or allocate one more byte), so the zero terminator won't be written out of bounds.

Compare two strings character by character in C

I have one 'simple' (I hope) question. I am actually coding some little program and I need to compare two strings, same length, but different letters like
Eagle
and
Hdjoh
I want to compare the first letter of the first string with the first letter of the second string,
the second letter of the first string with the second letter of the second string etc..
I started to do like this:
for(i=0, i<N, i++){
for(j=0, j<N, j++){
if(string1[i]==string1[j] etc.. etc..
}
}
I see clearly that it doesn't compare first letter with first letter, second with second etc..
So maybe anyone have an idea how can I do this? (Without using any functions of string.h, i want to do this ''on my own'').
Maybe its a stupid question but im still a novice in C so...
Ah and the last thing, I define the two strings with 5 characters in my example, but it could be more than 5 vs 5..
Thanks by advance for the ideas.
Edit 1 :
#include <stdio.h>
#define N 20
int main()
{
unsigned char string1[N], string2[N];
int Answer=0, i=0;
scanf("%s", string1);
scanf("%s", string2);
for(i=0; i<N; i++){
if(string1[i]==string2[i]){
Answer=1;
}
else{
Answer=0;
}
}
printf("Answer = %d", Answer);
return 0;
}
Why are you using a nested for loop for this? If both strings are of size n do this:
for(int i=0;i<n;i++){
if(string1[i]==string2[i]){
//do something
else if(// lesser than condition)
//do something else
else if(//greater than condition)
//do something else other than the previous something
}
Here you when i=0, you are comparing string1[0] with string2[0], when i=1, you compare string1[1] with string2[1] and so on.....
Your approach with nested loops isn't very well thought-out.
Clearly it will compare all letters of the second string against the first letter of the first string, then do the same for the second letter of the first string, and so on. Not at all the desired behavior.
Re-implementing strcmp() isn't very hard, here's a shot:
int my_strcmp(const char *a, const char *b)
{
for(; *a && *b && *a == *b; ++a, ++b)
;
if(*a < *b)
return -1;
return *a > *b;
}
Note that it returns zero when the strings are equal. A good way to write a test is:
if(my_strmcp(a, b) == 0)
{
printf("two equal strings: '%s' and '%s'\n", a, b);
}
Some people write it as if(!my_strcmp()) but I don't recommend that, since it's mashing up so many concepts.
You want to use the same index for both strings to compare:
unsigned len = strlen(s1);
assert(len == strlen(s2) && "Strings not the same length");
for (unsigned i = 0; i < len; i += 1)
{
if (s1[i] != s2[i])
return false; /* strings are not equal */
}
return true; /* strings are equal */
Make sure that the strings have the same encoding, either ASCII or UTF8 or whatever. Comparing strings of different encoding will cause trouble :)
This code compares character by character. Note that this is not suitable for crypto code as it is vulnerable to a timing attack
for(i=0; i<N; i++){
if(string1[i]==string2[i]){
equal = 1;
}else{
equal = 0;
break;
}
}
Notes:
I am assuming same length (as stated in question)
I am also assuming strings are non-zero length
Both of these assumptions may not be true in other code.
Simple compare each element until the end of string is found or a difference.
size_t i = 0;
while (string1[i] != '\0' && string1[i] == string2[j]) i++;
int StringTheSame = string1[i] == string2[j];
This ignores N, but stops when either end-of-string ('\0') is encountered.
[Edit] #Kartik_Koro suggested a concern about a timing attack. Following is a constant time solution
int diff_bits = 0;
for(size_t i=0; i<N; i++) {
diff_bits |= string1[i] ^ string2[i];
}
int equal = diff_bits == 0;
The above has a problem if either string's length is shorted than N-1, but per OP's requirements, that should not happen.

Entering a letter then minus to the alphabet

i am making a program that discard a letter from a list if you enter a letter, can anyone help me. thanks.
in example:
(BEFORE)
ABCDEFGHIJKLMNOPQRSTUVWXYZ
enter a letter: A
(AFTER ENTERING A LETTER 'A')
_BCDEFGHIJKLMNOPQRSTUVWXYZ
enter a letter:
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <windows.h>
int main()
{
int alphabet[26];
char letter;
int i;
int j;
alphabet[0] = 'A';
for(i = 0;i < 26; i++)
{
alphabet[i] = alphabet[0];
printf ("%c", alphabet[i], alphabet[i]);
alphabet[0]++;
}
printf("\n\nenter the letter you want to remove in the alphabet: ");
scanf("%c", letter);
while(j<alphabet[i])
{
if(letter==alphabet[i])
{
j--;
}
}
}
The problem is its not removing the letter in the alphabet when i entered the letter i want to remove. please help. thanks.
EDIT: one last thing, how can i make it only one input?, i mean if i input the same letter in 2nd time it will said "you already input that letter".
You are assuming that the letters are contiguos, as in ASCII, but you cannot assume that in C.
The next line has a duplicated argument:
printf ("%c", alphabet[i], alphabet[i]);
Drop the last alphabet[i].
Your last if() sentence is wrong: the comparisson must be done with ==.
It is not clear at all what do you want to do.
EDIT:
I would do the program in this way:
#include <stdio.h>
int main()
{
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char letter;
printf("Choose a letter: ");
letter = getchar();
printf("\n\n");
for(int i = 0; i < 26; i++)
if (letter == alphabet[i])
{
alphabet[i] = '_';
break; /* This terminates the for() loop */
}
printf("Result: %s \n", alphabet);
}
EDIT2: I have changed the declaration of alphabet, because the string constant has to be modified later...
you are assigning a value to letter with the the statement
letter=alphabet[i]
this statement will always be true, unless alphabet[i] is 0.
use comparision instead
letter==alphabet[i]
also your while loop is a bit weird, as the value of j will be undefined in the beginning , so your comparision will be undefined.
while(j<alphabet[i])
{
if(letter=alphabet[i])
{
j--;
}
probably you simply want to do something like:
for(i = 0;i < 26; i++) {
if(alphabeth[i]==letter) {
alphabeth[i]='_';
}
}
if you only want to replace the first occurence of the letter, insert a break; after alphabeth[i]='_';
and you probably don't want to have magic values like "26" occuring multiple times in your sourcecode.
instead use something like
#define ALPHABETSIZE 26
and replace all occurences of 26 by ALPHABETSIZE
There are a few things here that you are doing to make it hard for yourself.
You need to use "==" not "=" to compare two variables
Your value for "j" is not initialised so "j--" would be undefined
Its probably better to keep all your types the same and make the array a "char" array not an "int" array.
To remove an element from your array "int alphabet[26];" would be very difficult, it would probably be easier to make this a "string" exercise. All you can really do is to make a "blank" letter by
alphabet[j] = ' ';
I think its possible to make a better design though if you explain your requirements more clearly :)
If I got you right you want to go through your array and check if the entered char matches any in the array.
Is there any reason, why you dont use a for-loop like this and set the array position to 0 instead of the while statement?
for(i=0;i<26;i++)
{
if(letter == alphabet[i])
alphabet[i] = "_"; // or setting it to 0 if you use and int-array
}
Or do I get something wrong here?

Resources