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 2 years ago.
Improve this question
Given a 2D array of size 100 x100 of characters and a word (1D character array), find the occurrences of given word in 2D array (search only left to right horizontally).
char data[100][100] =
{
"ACFRTBOOK",
"BOPNBOOKQUIZGEEK",
"IDEQAPRACTICE"
};
char Word[4] = "BOOK";
Output:
pattern found at 0, 5
pattern found at 1, 4
This might help:
int k = 0, n = 0;
char word[] = "BOOK";
for (int i = 0; i < size - 1; i++)
{
for (int j = 0; data[i][j] != '\0'; j++)
{
n = j;
while (data[i][n] == word[k] && word[k] != '\0')
{
n++;
k++;
if (word[k] == '\0')
{
printf("Found at %i, %i", i, j)
}
}
k = 0;
}
}
Firstly, you cannot initialize a char array as a String like you did with char Word[4] = "BOOK"; this would have to be char word[4] = {'b','o','o','k'}; The same applies to your 2D array named data.
So here is how you would do such a thing. I added in //comments to explain, but the general idea is to turn the arrays into Strings as these are easier to use when locating another set of characters.
Please let me know if you need further assistance. I hope this helps.
public void findWord(char[] word; char[][] data){
String w = new String(word); //it is much easier to work with strings for a searching problem like this
int x=0,y=0;
for(char[] i:data){//iterates through each row of data
String d = new String(i);
while(d.contains(w)){
x+=i.indexOf(w);//locates the pattern
System.out.println("pattern found at " + x + ", " + y);
x++;
d=s.substring(x);//this removes the previous occurance of the patern so that the index of can find a new repeat in the same row
}
y++;
x=0;//reset for next array
}
}
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I need to convert an integer into a bit string in C. I have written a function to achieve this (example) & need to know a better solution for it.
eg:
char* int_to_bin(int n)
{
char arr[] = "00000000000000000000000000000000"; // 32 zeros , coz int => 32 bit
int pos = 0;
while(n!=0)
{
char element = (n%2==0)?'0':'1';
arr[pos] = element;
n /= 2;
pos++;
}
char *str = malloc(sizeof(char)*(pos+1)); // need to malloc for future use
for(int i = 0; i<pos; i++) // get the reverse
{
*(str+i) = arr[pos-1-i];
}
*(str+pos) = '\0';
return str;
}
You can avoid the memory copy and let the compiler unroll the loop by using a fixed number of iterations:
char* int_to_bin(unsigned n) {
unsigned size = sizeof(n) * CHAR_BIT;
char* str = malloc(size + 1);
str[size] = 0;
while(size--) {
str[size] = '0' + (n & 1);
n >>= 1;
}
return str;
}
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 3 years ago.
Improve this question
#include <stdio.h>
#define NO_OF_CHARS 256
bool areAnagram(char* str1, char* str2) {
// Create 2 count arrays and initialize all values as 0
int count1[NO_OF_CHARS] = { 0 };
int count2[NO_OF_CHARS] = { 0 };
int i;
for (i = 0; str1[i] && str2[i]; i++) {
count1[str1[i]]++;
count2[str2[i]]++;
}
if (str1[i] || str2[i])
return false;
for (i = 0; i < NO_OF_CHARS; i++)
if (count1[i] != count2[i])
return false;
return true;
}
int main() {
char str1[] = "geeksforgeeks";
char str2[] = "forgeeksgeeks";
if (areAnagram(str1, str2))
printf("The two strings are anagram of each other");
else
printf("The two strings are not anagram of each other");
return 0;
}
When i = 0; then count1[str[i]]++ will contain count1['g']++ and count1 is an array of 256 size each initialised with 0.
My question here is: In which index (from 0 to 256) of count1, count1[g] will get stored and after getting stored on that index what it will do next?
using ASCII code for each char:
g - 103 - 01100111
so count1['g'] = count1[103]
after that, every char have its count on count1 for string1 and count2 for string2, then the next code compares its count and returns true if the count is the same.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
How can I store the first character of an element in a string? E.g. if I run
for (j=0; j < 5; j++) {
printf("%s\n, string[j]);
}
I get
hello
how
are
you
Thanks to the answer provided by #Holy semicolon, I know that I can run printf("%c\n, string[j][0]); to print the first letters:
h
h
a
y
However, how can I store the first letters in a new array?
So far, I have:
char secondStr[10];
for (j=0; j<5; j++) {
secondStr[j] = string[j][0];
}
This results in an error assignment makes pointer from integer without a cast
I know this question is slightly different to the one I asked before (regarding printing the first elements) - I was unsure whether or not to ask an entirely new question on SO. I apologise in advance if I was supposed to ask a new question.
when you have an array of pointers to char *string1[] = {"hello", "how", "are", "you"}; and you want to print the first string of it hello so you must use %s for string like this printf("%s",string1[0]) but if you want to print the first char of the first string you need to use %c like this printf("%c",string1[0][0]).
#include <stdio.h>
int main()
{
char *string1[] = {"hello", "how", "are", "you"};
printf("%s",string1[0][0]); // I think you did this fault It'll give you Segmentation fault
return 0;
}
so as you see in the code above you need to replce %s with %c.
Edit
What if I wanted to store the first letters in a new list?
you will need then to allocate memory to the new string.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *string1[] = {"hello", "how", "are", "you"};
char **keep = calloc(sizeof(char*),5); //memory allocating
for (int index = 0; index <= 3; index++)
{
keep[index] = calloc(sizeof(char),2); //memory allocating
keep[index][0] = string1[index][0];
keep[index][1] = '\0';
}
//for test
for (int i = 0; i <= 3; i++)
printf("%c\n",keep[i][0]);
return 0;
}
If string is std::string, then:
string s[6] = { "hello","how", "are", "you", "?" };
for (int j = 0; j < 5; j++)
{
if(s[j].size())
printf("%c\n", s[j].c_str()[0]);
}
Should word.
Many options are there. I will just mention some.
Use begin()
for( int i = 0 ; i < num ; i++ )
{
string:: iterator it = String[i].begin();
cout << *it;
}
Use front()
for( int i = 0 ; i < num ; i++ )
{
cout << String[i].front();
}
Use at()
for( int i = 0 ; i < num ; i++ )
{
cout << String[i].at();
}
You can just go through the member functions of string and use it to your purpose
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Here is a part of code which describes a function to reverse characters of a string
(Based on exercise 1-19 of Brian W. Kernighnan Programming in C)...
( I have googled various text reverse function, but all of them us pointers or using strrev(), but I don't have an idea what a pointer is.... nor do I want to use strrev(), hence I made a reverse string function as the author wanted it to be........ )
The function:
void reverse(char s[])
{
int i , n ;
char j ;
i = 0 ;
while(s[i] != '0') //And not EOF
{
++n;
}
for(i = 0; i < n; ++i)
{
j = s[i] ;
s[i] = s[n - 1] ;
s[n - 1] = j ;
}
}
However I think overwritting arrays is bad , and the whole function seems awry.
P.S : It would be great if you did check and help me with the whole code here, since it would be offtopic if I did post it here, The code's main return 0; however it still doesn't work....
[EDIT]
Ok I am seriously sorry for troubling you for a typo... I can't delete this question since it has answers with upvotes however I'm sorry....
The correct function would be :
void reverse(char s[])
{
int i, l;
char temp;
for (l = 0; s[l] != '\0'; ++l);
l--;
for (i = 0; i < l; ++i) {
temp = s[i];
s[i] = s[l-1];
s[l-1] = temp;
--l;
}
}
Full Code is here :
Code
Code Working is here :
UPDATE:
I created a correct and working solution for the word 'hello':
#include <stdio.h>
int main(void)
{
char s[] = "hello";
char temp;
// do the swapping here..
temp = s[0];
s[0] = s[4] ;
s[4] = temp ;
temp = s[1] ;
s[1] = s[3] ;
s[3] = temp ;
temp = s[2] ;
s[2] = s[2] ;
s[2] = temp ;
printf("%c, %s ", temp, s);
}
I don't know where you got this piece of code, but it's actually quite broken:
n is never initialized. This is undefined behavior.
The while loop won't terminate at all because it compares a char with a value that is not in the range of a char.
The while loop can't do anything sensible since its body can't change the loop condition.
The for loop exchanges all characters with one single array element, which effectively rotates the string right by one char. But the program will never reach this point anyway.
The loop
while(s[i] != EOF)
{
++n;
}
seems wrong.
String end is checked via 0, not via EOF.
You never change i, so that you always check s[0].
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
So I was writing a C program to make use of caesar algorithm using a custom table, where I will give the table and shifting will be done using that table e.g the text "abc" according to table "abc" with key=1 should be ciphered as bca, however i am having difficulty on the last characters if key+index of letter is higher than the length of the table stored here is my code
void encrypt (char table[],char entext[],char text[],int key)
{
int i,j;
int k = strlen(table);
//int result = (key + k);
for (i=0;i<strlen(table);++i)
{
j = 0;
if (text[i]!='\0')
{
while (text[i]!=table[j])
{
j++;
}
if ((j+key)>k)
{
j=(j+key)%k;
//j = (result - j);
}
else
j = j + key;
entext[i] = table[j];
}
}
entext[i+1] = '\0';
puts(entext);
}
int main()
{
char table[100] , text[100] , entext[100] , c;
int i , j , key;
printf("Enter the text : ");
gets(text);
printf("Enter the table : ");
gets(table);
printf("Enter the key : ");
scanf("%d",&key);
encrypt(table,entext,text,key);
system("pause");
return 0;
}
if ((j+key)>k)
should be
if ((j+key)>=k)
Besides, this check is completely unnecessary because of how mod works. I will take the liberty to rewrite your code so it looks nicer:
void encrypt (char table[],char entext[],char text[],int key)
{
int i,j;
int k = strlen(table);
//int result = (key + k);
for (i=0;i<strlen(table);++i)
{
if (text[i]!='\0')
{
for(j=0; text[i] != table[j] ;j++);
entext[i] = table[(j+key)%k];
}
}
entext[i+1] = '\0';
puts(entext);
}
I believe you could make this "table" lookup more efficient by indexing the value of the char itself, but unless you are dealing with pretty big input, this won't really make a difference.
void encrypt (char table[], char entext[], char text[], int key) {
int i,j;
int k = strlen(table);
for (i=0;text[i];++i){
for(j=0;table[j] && text[i]!=table[j];++j)
;
if(table[j]=='\0')//character not find at table
entext[i] = text[i];//Not slide. // or Error?
else {
j += key;
if(j>=k)
j -= k;//j = j % k
entext[i] = table[j];
}
}
entext[i] = '\0';
puts(entext);
}