remove duplicates in a string with a buffer [closed] - c

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 1 year ago.
Improve this question
I’m trying to remove duplicates in a string using a map. Running it through GDB I'm not able to figure out where the code is failing, though the logic to me seems right.
Could anyone please point out the mistake?
int main() {
char *str="I had my morning tea";
int len = strlen(str);
int dupArr[256] = {0};
//Build the map
int i=0;
for(i;i<256;i++)
dupArr[str[i]]++;
//If the count is 1 then print that value.
i=0;
for(i;i<256;i++) {
if(dupArr[str[i]] == 1) {
printf("%c\n",str[i]);
}
}
}
output
I h y o r i g t % c 4 # } ` 8 � F J
I get up to 't' ,which is correct but then i see magic chars.

Your string has length of len but you are traversing till 256 which is out of bound.
Use len when inserting into the hash.
int i=0;
for(i;i<LEN;i++)
dupArr[str[i]]++;
Also if your are checking the duplicates then it should be bigger than 1 since your are ++ the first encountered char
if(dupArr[str[i]] > 1)

In addition to Mark Ezberg's good answer, note that dupArr[str[i]]++; poses a problem when str[i] < 0.
Better to treat the characters as unsigned char:
int dupArr[UCHAR_MAX + 1] = {0};
....
dupArr[(unsigned char) str[i]]++;
Rolling this and other ideas together:
int main(void) {
char *str="I had my morning tea";
size_t dupArr[UCHAR_MAX + 1] = {0};
unsigned char *s = (unsigned char *) str;
while (*s) {
dupArr[*s]++;
s++;
}
for(unsigned i = 0; i <= UCHAR_MAX; i++) {
// A duplicate is when dupArr[i] is _more_ than 1.
if(dupArr[i] > 1) {
printf("%c\n",str[i]);
}
}
}

Related

Search a Word in a 2D characters array [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 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
}
}

What is wrong with my C code? C code error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am very new in C programming. can someone please tell me what is wrong with this code I am trying to run this code.
int main(void)
{ char source[10];
char *dest; size_t i;
strcpy(source, "0123456789");
dest = malloc(strlen(source));
for (i = 1; i <= 11; i++) {
dest[i] = source [i];
}
dest[i] = '\0';
printf("dest = %s", dest); return 0; 13. }
Thanks a lot in advance
Firstly, allocate enough memory for source to hold 0123456789. And this dest[i] = '\0'; causes undefined behavior as here you are trying to access(dest[10]) something which you didn't allocate. So allocate enough memory for dest to store '\0' at the end. For e.g
dest = malloc(strlen(source) + 1);/* +1 is for \0 char as strlen(source) doesn't include \0 */
Secondly, don't think that source[0] is integer zero 0 its a character zero i.e '0'(ascii - 48). So you no need to start rotating form i=1, rotate from i=0 and upto '\0'.
This
for (i = 1; i <= 11; i++) { /* array index starts from 0 */
dest[i] = source [i];
}
Should be
for (i = 0;source[i]; i++) { /* when \0 encounters, loop terminates */
dest[i] = source [i];
}

Is this reverse string function in C poorly written ? / How to make this code better? [closed]

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].

How to find whether the string is a Lapindrome? [closed]

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 9 years ago.
Improve this question
The following code is giving correct output as given on the codechef problem page: http://www.codechef.com/problems/LAPIN
but getting wrong answer on submission
please tell me the possible problem with my code
here is the question
Lapindrome is defined as a string which when split in the middle, gives two halves having the same characters and same frequency of each character. If there are odd number of characters in the string, we ignore the middle character and check for lapindrome. For example gaga is a lapindrome, since the two halves ga and ga have the same characters with same frequency. Also, abccab, rotor and xyzxy are a few examples of lapindromes. Note that abbaab is NOT a lapindrome. The two halves contain the same characters but their frequencies do not match.
Your task is simple. Given a string, you need to tell if it is a lapindrome.
Input:
First line of input contains a single integer T, the number of test cases.
Each test is a single line containing a string S composed of only lowercase English alphabet.
Output:
For each test case, output on a separate line: "YES" if the string is a lapindrome and "NO" if it is not.
and here is the code
#include<stdio.h>
#include<string.h>
int main()
{
int f,t,mid,len;
char arr[1000];
int left[125],right[125];
scanf("%d",&t);
for(int i=0;i<t;i++)
{
f=0;
scanf("%s",arr);
memset(left,0,sizeof(left));
memset(right,0,sizeof(right));
len=strlen(arr);
for(int i=0;i<len/2;i++)
left[arr[i]]++;
for(int i=(len+1)/2;i<len;i++)
right[arr[i]]++;
for(int i=0;i<strlen(arr);i++)
{
if(left[arr[i]]!=right[arr[i]])
f++;
break;
}
if(f==0)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
I recommend you read up on modularity; it'll make your life easier.
#include <stdio.h>
#define BOOL unsigned char
#define TRUE 1
#define FALSE 0
unsigned string_length(char *string)
{
unsigned counter = 0;
while (string[counter++] != '\0') { }
return counter - 1;
}
BOOL are_equal(unsigned *a, unsigned *b, int size)
{
int i;
for (i = 0; i < size; ++i)
{
if (a[i] != b[i])
{
return FALSE;
}
}
return TRUE;
}
BOOL is_lapindrome(char *string)
{
unsigned left[26] = { 0 }, right[26] = { 0 },
str_len = string_length(string);
if (str_len < 2)
{
return FALSE;
}
int i;
for (i = 0; i <= str_len / 2 - 1; ++i)
{
left[string[i] - 'a']++;
}
for (i = (str_len + 1) / 2; i < str_len; ++i)
{
right[string[i] - 'a']++;
}
return are_equal(left, right, 26);
}
int main()
{
char *list[6] =
{
"gaga",
"abcde",
"rotor",
"xyzxy",
"abbaab",
"ababc"
};
int i;
for (i = 0; i < 6; ++i)
{
printf("%s\n", is_lapindrome(list[i]) == TRUE ? "YES" : "NO");
}
return 0;
}
Your buffer is one byte too short - a string of 1000 characters requires 1001 chars, the last one taken by the nul terminator.
"lowercase English alphabet" sounds a bit ambiguous - I'd say that by some interpretation, it could contain spaces. If so, the input will be read incorrectly.
I can't see other problems right now, but I'd strongly suspect the first one.

removing chars from a string - 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 8 years ago.
Improve this question
Suppose I have a char* word = "abaradasaddragfavvdavgasbga00rarcrawabr0ac0ra0ra0vra0"
and I want to remove all the '0' chars from the word, in place, without using extra-memory or memmove. How could I do it?
So the output would be: "abaradasaddragfavvdavgasbgararcrawabracraravra"
** What I have tried **:
void removeZeros( char* word) {
int size = strlen( word );
int i;
for( i = 0; i < size; i++ ){
if( word[i] == '0' ){
word[ i ] = word[ i + 1 ];
i++;
}
}
}
* Rules **:
should be done in place
should not call any built-in function like memmove or remove
should not use extra-memory
should not assign it to another variable
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
char word[] = "abaradasaddragfavvdavgasbga00rarcrawabr0ac0ra0ra0vra0";
int size = strlen( word ) + 1;
std::remove(word, (sizeof(char) * size) + word, '0');
std::cout << word;
}
// this assumes your variable word is really a cstr and is NULL terminated
// also, it assumes that it's not in read only memory space like your small
// example shows but is actually in-place writeable
char* write_position = word;
char* scan_position = word;
for( ; *scan_position != '\0'; scan_position++ ) {
if( *scan_position == '0' ) continue;
*(write_position++) = *scan_position;
}
*write_position = '\0';
Iterate over the string from start to end. For each 0 you find, increment an integer called offset, say. For every non-0 character, move it down by the current value of offset. Make sure to put a null byte on the end.

Resources