This is a picture when I use fgets. (it does not work properly, insanely slow !!)
and This is a picture when it comes to gets. (works fine)
# define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
struct sNode {
struct sNode* tNode;
int G[20];
};
struct tNode {
struct tNode* prev;
struct tNode* next;
int data;
int used;
};
int convert_input(struct sNode** t_ArrayRef, char string[200])
{
int j = 0, i = 0, temp = 0;
int K[20];
while (string[i] != '\0')
{
temp = 0;
while (string[i] != ' ' && string[i] != '\0')
temp = temp * 10 + (string[i++] - '0');
if (string[i] == ' ')
{
i++;
}
(*t_ArrayRef)->G[j++] = temp;
}
return j - 1;
}
int main() {
int i;
char string[200];
char* str[5];
struct sNode* t = (struct sNode*)malloc(sizeof(struct sNode));
str[0] = string;
//fgets(str[0], sizeof(str[0]), stdin); // doesn't works !!!
gets(str[0]); // works !!!
int c = convert_input(&t, str[0]);
int num = t->G[0];
const int a = num;
struct tNode* tNod[6000];
for (i = 0; i<num; i++) {
tNod[i] = (struct tNode*)malloc(sizeof(struct tNode));
}i = 0;
for (i = 1; i<num; i++) {
tNod[i - 1]->data = i;
tNod[i - 1]->used = 0;
if (i != num - 1) {
tNod[i - 1]->next = tNod[i];
}
else {
tNod[i - 1]->next = tNod[i];
tNod[i]->data = i + 1;
tNod[i]->next = tNod[0];
}
}i = 0;
struct tNode* current;
i = 1; int j = 0; int fCount = 0; int zCount = 0;
current = tNod[i - 1];
printf("<");
while (fCount == 0) {
while (current->used == 1) {
current = current->next;
j++;
if (j > num) {
fCount = 1;
break;
}
}
j = 0;
if (i % t->G[1] == 0 && fCount == 0) {
zCount++;
if (zCount != t->G[0]) {
printf("%d, ", current->data, i);
current->used = 1;
}
else {
printf("%d", current->data, i);
current->used = 1;
}
}
i++;
current = current->next;
}
printf(">");
return 0;
}
Could anyone explain to me why I can't get it working using fgets ?
When you use
fgets(str[0], sizeof(str[0]), stdin);
you do not pass the correct size: sizeof(str[0]) is the size of a pointer to char, not the size of the 200-byte char array that you stored in it.
The compiler resolves this sizeof operator at compile time. It has no idea about the value that you put into element zero. In fact, it ignores zero altogether, replacing with sizeof(*str).
Fix this problem by passing the proper size:
fgets(str[0], sizeof(string), stdin);
Related
Im trying to write a very simple compressor in C and I ran into the error "Heap has been corrupted" in my code. I looked into it, and the error seems to come because of this line:
ptr = (char*)malloc(count * sizeof(char));
when i change the size from count to 1000 it works, and i tried debugging and seeing if there is a difference somewhere but i couldnt find it, i understand there might be somekind of an overflow but i dont understand why and whats the solution instead of just writing a big number to fix it
this is my code for now:
#include <stdio.h>
#include <stdlib.h>
errno_t err;
int count =0;
struct node {
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int data) {
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
};
int* frequency(char* str) {
FILE* fptr;
err = fopen_s(&fptr, str, "r");
if (err != 0)
{
printf("The file wasn't opened\n");
exit(0);
}
int* ptr;
ptr = (int*)malloc(95 * sizeof(int));
if (ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
for (int i = 0; i < 95; i++) {
*(ptr + i) = 0;
}
char ch;
int index;
while ((ch = fgetc(fptr)) != EOF) {
index = (int)ch - 32;
(*(ptr+index))++;
}
err = fclose(fptr);
if (err != 0)
{
printf("The file wasn't closed\n");
exit(0);
}
for (int i = 0; i < 95; i++) {
printf("%d ", *(ptr+i));
}
return ptr;
}
void* letFrequency(int* occLet) {
for (int i = 0; i < 95; i++) // counts how many actually occur
{
if (*(occLet+i) > 0)
{
count++;
}
}
int* ptr;
ptr = (char*)malloc(count * sizeof(char));
if (ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
int max = 0;
int placement = 0;
for (int j = 0; j < count; j++) {
for (int i = 0; i < 95; i++) {
if (*(occLet+i) >= max)
{
max = *(occLet+i);
placement = i;
}
}
*(ptr+j) = (char)(placement + 32);
printf("%c", *(ptr +j));
*(occLet+placement) = 0;
max = 1;
}
return ptr;
}
void binaryMap(char* letFrq) {
struct node* rootzero = newNode(1);
struct node* rootone = newNode(0);
int leaveszero = 0;
int leavesone = 0;
if (count % 2 == 0) {
leavesone = count / 2;
leaveszero = count / 2;
}
else
{
leavesone = count / 2;
leaveszero = count / 2 + 1;
printf("%d", leaveszero);
}
}
int main() {
char str[70];
printf("Enter the name of the text file you want to compress: ");
scanf_s("%s", str, sizeof(str));
int* ptrFr;
char* ptrLetFr;
ptrFr = frequency(str);
ptrLetFr = letFrequency(ptrFr);
free(ptrFr);
binaryMap(ptrLetFr);
}
The lines;
int* ptr;
ptr = (char*)malloc( count * sizeof(char));
are clearly erroneous. If you intended count integers, then sizeof(char) will allocate too small a block. I suggest as a habit:
Do not cast void* - just assign it.
Use sizeof the object pointed to, not an explicit type.
Do not leave dangling pointers unnecessary.
To that end:
int* ptr = malloc(count * sizeof(*ptr) ) ;
Or if it were _intended to be char* then:
char* ptr = malloc(count * sizeof(*ptr) ) ;
Note how minimal the change is - you don't have to correct it three different places.
I'm working on a program that takes in a string from the command line, separates the words where there is a non-alphabetic character, and inserts them into a linked list. So for example, hello1world would be separated into "hello" and "world". However when I comment out the first printf statement (shown below), the program doesn't print out the first word in the linked list. When the printf statement exists, the code works fine. Any help would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct _Node {
char * string;
struct _Node * next;
} Node;
Node * head = NULL;
int isSeperator(int ch) {
if(isalpha(ch)) {
return 0;
} else {
return 1;
}
}
void addToList(char * comp) {
Node * temp = NULL;
temp = malloc(sizeof(Node));
temp->string = comp;
temp->next = head;
head = temp;
}
int main(int argc, char * argv[]) {
head = malloc(sizeof(Node));
int i, j, len, lastPos, compLen;
for(i = 1; i < argc; i++) {
lastPos = 0;
char * str;
str = (char*)malloc(sizeof(argv[i]) + 1);
strcpy(str, argv[i]);
strcat(str, "\0");
len = strlen(str);
for(j = 0; j < len; j++) {
compLen = j - lastPos;
char comp[compLen + 1];
if(isSeperator(*(str + j)) == 1) {
memcpy(comp, &str[lastPos], compLen);
strcat(comp, "\0");
addToList(comp);
lastPos = j + 1;
} else {
if(j == len - 1) {
memcpy(comp, &str[lastPos], compLen + 1);
strcat(comp, "\0");
addToList(comp);
}
}
//printf("%s \n", head->string);
}
printf("%s! \n", head->string);
}
return 0;
}
I'm doing a shift-reduce algorithm for our compiler design subject. This is the code.
void shiftReduce(char str[MAX_CHAR], int prodNum, int line)
{
int limit = 5, y=0;
int substrFlag = 1; //0 true 1 false
int ctr,x, counter;
int match, next;
char stack[MAX_CHAR];
clearString(stack);
OUTER:while ((strcmp(stack, prod[0].left) != 0) && (y < limit))
{
addChar(stack, str[0]);
strcpy(str, dequeue(str));
printf("Stack = %s\nQueue = %s\n", stack, str);
for (ctr = 0; ctr < prodNum; ctr++)
{
if (strstr(stack, prod[ctr].right) != NULL)
{ //substring found
substrFlag = 0;
strcpy(stack, replace(stack, prod[ctr].right, prod[ctr].left));
goto OUTER;
}
}
if ((str[0] == '\n') || (str[0] == '\0'))
y++;
}
if (strcmp(stack, prod[0].left) == 0)
;//printf("%s - Accepted.\n", stack);
else
printf("Syntax error on line %i\n", line);
}
When I comment the printf("Stack = %s\nQueue = %s\n", stack, str); line, it works well. But when I uncomment it, it returns the code 3221225477.
BTW. This is the dequeue function:
char * dequeue (char str[MAX_CHAR])
{
int x = 0; char temp;
for (x = 0; x < length(str); x++)
{
if ((x+1) < length(str))
str[x] = str[x+1];
}
return str;
}
and the addChar function:
void addChar (char * str, char letter)
{
int a = 0;
while (str[a] != '\0')
a++;
str[a] = letter;
str[a+1] = '\0';
return;
}
and finally replace function.
char * replace (char orig[MAX_CHAR], char substr[MAX_CHAR], char rep[MAX_CHAR])
{
int match, end=0, next=0;
int flag = 0; //0 true 1 false
char temp [MAX_CHAR];
char store[MAX_CHAR];
if (strstr(orig, substr) == NULL)
return NULL;
int x,y;
for (x = 0; x < length(orig); x++)
{
if (orig[x] == substr[0]) //if current character is equal to first character of substring
{
match = x;
for (y = 0; y < length(substr); y++)
{
if (orig[match+y] != substr[y])
{
flag = 1;
break;
}
}
if (flag == 0)
{
next = match + length(substr);
for (y = 0; y < length(rep); y++)
{
temp[match+y] = rep[y];
end = (match+y);
}
for (y = next; y < length(orig); y++)
{
temp[y] = orig[next+(y-next)];
}
return temp;
}
}
else
{
addChar(temp, orig[x]);
}
}
return temp;
}
PS. The prod array:
struct RULES
{
char left[MAX_CHAR];
char right[MAX_CHAR];
} RULES;
struct RULES prod[MAX_RULES];
When I comment the printf("Stack = %s\nQueue = %s\n", stack, str); line, it works well. But when I uncomment it, it returns the code 3221225477.
Then most likely either stack or str has not been 0-terminated or points to invalid memory.
How can I count the number of occurrences in c of each letter (ignoring case) in the string? So that it would print out letter: # number of occurences, I have code to count the occurences of one letter, but how can I count the occurence of each letter in the string?
{
char
int count = 0;
int i;
//int length = strlen(string);
for (i = 0; i < 20; i++)
{
if (string[i] == ch)
{
count++;
}
}
return count;
}
output:
a : 1
b : 0
c : 2
etc...
Let's assume you have a system where char is eight bit and all the characters you're trying to count are encoded using a non-negative number. In this case, you can write:
const char *str = "The quick brown fox jumped over the lazy dog.";
int counts[256] = { 0 };
int i;
size_t len = strlen(str);
for (i = 0; i < len; i++) {
counts[(int)(str[i])]++;
}
for (i = 0; i < 256; i++) {
if ( count[i] != 0) {
printf("The %c. character has %d occurrences.\n", i, counts[i]);
}
}
Note that this will count all the characters in the string. If you are 100% absolutely positively sure that your string will have only letters (no numbers, no whitespace, no punctuation) inside, then 1. asking for "case insensitiveness" starts to make sense, 2. you can reduce the number of entries to the number of characters in the English alphabet (namely 26) and you can write something like this:
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
const char *str = "TheQuickBrownFoxJumpedOverTheLazyDog";
int counts[26] = { 0 };
int i;
size_t len = strlen(str);
for (i = 0; i < len; i++) {
// Just in order that we don't shout ourselves in the foot
char c = str[i];
if (!isalpha(c)) continue;
counts[(int)(tolower(c) - 'a')]++;
}
for (i = 0; i < 26; i++) {
printf("'%c' has %2d occurrences.\n", i + 'a', counts[i]);
}
Like this:
int counts[26];
memset(counts, 0, sizeof(counts));
char *p = string;
while (*p) {
counts[tolower(*p++) - 'a']++;
}
This code assumes that the string is null-terminated, and that it contains only characters a through z or A through Z, inclusive.
To understand how this works, recall that after conversion tolower each letter has a code between a and z, and that the codes are consecutive. As the result, tolower(*p) - 'a' evaluates to a number from 0 to 25, inclusive, representing the letter's sequential number in the alphabet.
This code combines ++ and *p to shorten the program.
One simple possibility would be to make an array of 26 ints, each is a count for a letter a-z:
int alphacount[26] = {0}; //[0] = 'a', [1] = 'b', etc
Then loop through the string and increment the count for each letter:
for(int i = 0; i<strlen(mystring); i++) //for the whole length of the string
if(isalpha(mystring[i]))
alphacount[tolower(mystring[i])-'a']++; //make the letter lower case (if it's not)
//then use it as an offset into the array
//and increment
It's a simple idea that works for A-Z, a-z. If you want to separate by capitals you just need to make the count 52 instead and subtract the correct ASCII offset
#include <stdio.h>
#include <string.h>
void main()
{
printf("PLEASE ENTER A STRING\n");
printf("GIVE ONLY ONE SPACE BETWEEN WORDS\n");
printf("PRESS ENETR WHEN FINISHED\n");
char str[100];
int arr[26]={0};
char ch;
int i;
gets(str);
int n=strlen(str);
for(i=0;i<n;i++)
{
ch=tolower(str[i]);
if(ch>=97 && ch<=122)
{
arr[ch-97]++;
}
}
for(i=97;i<=122;i++)
printf("%c OCCURS %d NUMBER OF TIMES\n",i,arr[i-97]);
return 0;
}
After Accept Answer
A method that meets these specs: (IMO, the other answers do not meet all)
It is practical/efficient when char has a wide range. Example: CHAR_BIT is 16 or 32, so no use of bool Used[1 << CHAR_BIT];
Works for very long strings (use size_t rather than int).
Does not rely on ASCII. ( Use Upper[] )
Defined behavior when a char < 0. is...() functions are defined for EOF and unsigned char
static const char Upper[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const char Lower[] = "abcdefghijklmnopqrstuvwxyz";
void LetterOccurrences(size_t *Count, const char *s) {
memset(Count, 0, sizeof *Count * 26);
while (*s) {
unsigned char ch = *s;
if (isalpha(ch)) {
const char *caseset = Upper;
char *p = strchr(caseset, ch);
if (p == NULL) {
caseset = Lower;
p = strchr(caseset, ch);
}
if (p != NULL) {
Count[p - caseset]++;
}
}
}
}
// sample usage
char *s = foo();
size_t Count[26];
LetterOccurrences(Count, s);
for (int i=0; i<26; i++)
printf("%c : %zu\n", Upper[i], Count[i]);
}
You can use the following code.
main()
{
int i = 0,j=0,count[26]={0};
char ch = 97;
char string[100]="Hello how are you buddy ?";
for (i = 0; i < 100; i++)
{
for(j=0;j<26;j++)
{
if (tolower(string[i]) == (ch+j))
{
count[j]++;
}
}
}
for(j=0;j<26;j++)
{
printf("\n%c -> %d",97+j,count[j]);
}
}
Hope this helps.
#include<stdio.h>
#include<string.h>
#define filename "somefile.txt"
int main()
{
FILE *fp;
int count[26] = {0}, i, c;
char ch;
char alpha[27] = "abcdefghijklmnopqrstuwxyz";
fp = fopen(filename,"r");
if(fp == NULL)
printf("file not found\n");
while( (ch = fgetc(fp)) != EOF) {
c = 0;
while(alpha[c] != '\0') {
if(alpha[c] == ch) {
count[c]++;
}
c++;
}
}
for(i = 0; i<26;i++) {
printf("character %c occured %d number of times\n",alpha[i], count[i]);
}
return 0;
}
for (int i=0;i<word.length();i++){
int counter=0;
for (int j=0;j<word.length();j++){
if(word.charAt(i)==word.charAt(j))
counter++;
}// inner for
JOptionPane.showMessageDialog( null,word.charAt(i)+" found "+ counter +" times");
}// outer for
#include<stdio.h>
void frequency_counter(char* str)
{
int count[256] = {0}; //partial initialization
int i;
for(i=0;str[i];i++)
count[str[i]]++;
for(i=0;str[i];i++) {
if(count[str[i]]) {
printf("%c %d \n",str[i],count[str[i]]);
count[str[i]]=0;
}
}
}
void main()
{
char str[] = "The quick brown fox jumped over the lazy dog.";
frequency_counter(str);
}
Here is the C code with User Defined Function:
/* C Program to count the frequency of characters in a given String */
#include <stdio.h>
#include <string.h>
const char letters[] = "abcdefghijklmnopqrstuvwxzy";
void find_frequency(const char *string, int *count);
int main() {
char string[100];
int count[26] = { 0 };
int i;
printf("Input a string: ");
if (!fgets(string, sizeof string, stdin))
return 1;
find_frequency(string, count);
printf("Character Counts\n");
for (i = 0; i < 26; i++) {
printf("%c\t%d\n", letters[i], count[i]);
}
return 0;
}
void find_frequency(const char *string, int *count) {
int i;
for (i = 0; string[i] != '\0'; i++) {
p = strchr(letters, string[i]);
if (p != NULL) {
count[p - letters]++;
}
}
}
Have checked that many of the answered are with static array, what if suppose I have special character in the string and want a solution with dynamic concept. There can be many other possible solutions, it is one of them.
here is the solutions with the Linked List.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Node {
char data;
int counter;
struct Node* next;
};
void printLinkList(struct Node* head)
{
while (head != NULL) {
printf("\n%c occur %d", head->data, head->counter);
head = head->next;
}
}
int main(void) {
char *str = "!count all the occurances of character in string!";
int i = 0;
char tempChar;
struct Node* head = NULL;
struct Node* node = NULL;
struct Node* first = NULL;
for(i = 0; i < strlen(str); i++)
{
tempChar = str[i];
head = first;
if(head == NULL)
{
node = (struct Node*)malloc(sizeof(struct Node));
node->data = tempChar;
node->counter = 1;
node->next = NULL;
if(first == NULL)
{
first = node;
}
}
else
{
while (head->next != NULL) {
if(head->data == tempChar)
{
head->counter = head->counter + 1;
break;
}
head = head->next;
}
if(head->next == NULL)
{
if(head->data == tempChar)
{
head->counter = head->counter + 1;
}
else
{
node = (struct Node*)malloc(sizeof(struct Node));
node->data = tempChar;
node->counter = 1;
node->next = NULL;
head->next = node;
}
}
}
}
printLinkList(first);
return 0;
}
int charset[256] = {0};
int charcount[256] = {0};
for (i = 0; i < 20; i++)
{
for(int c = 0; c < 256; c++)
{
if(string[i] == charset[c])
{
charcount[c]++;
}
}
}
charcount will store the occurence of any character in the string.
//This is JavaScript Code.
function countWordOccurences()
{
// You can use array of words or a sentence split with space.
var sentence = "The quick brown fox jumped over the lazy dog.";
//var sentenceArray = ['asdf', 'asdf', 'sfd', 'qwr', 'qwr'];
var sentenceArray = sentence.split(' ', 1000);
var output;
var temp;
for(var i = 0; i < sentenceArray.length; i++) {
var k = 1;
for(var j = i + 1; j < sentenceArray.length; j++) {
if(sentenceArray[i] == sentenceArray[j])
k = k + 1;
}
if(k > 1) {
i = i + 1;
output = output + ',' + k + ',' + k;
}
else
output = output + ',' + k;
}
alert(sentenceArray + '\n' + output.slice(10).split(',', 500));
}
You can see it live --> http://jsfiddle.net/rammipr/ahq8nxpf/
//c code for count the occurence of each character in a string.
void main()
{
int i,j; int c[26],count=0; char a[]="shahid";
clrscr();
for(i=0;i<26;i++)
{
count=0;
for(j=0;j<strlen(a);j++)
{
if(a[j]==97+i)
{
count++;
}
}
c[i]=count;
}
for(i=0;i<26;i++)
{
j=97+i;
if(c[i]!=0) { printf("%c of %d times\n",j,c[i]);
}
}
getch();
}
protected void btnSave_Click(object sender, EventArgs e)
{
var FullName = "stackoverflow"
char[] charArray = FullName.ToLower().ToCharArray();
Dictionary<char, int> counter = new Dictionary<char, int>();
int tempVar = 0;
foreach (var item in charArray)
{
if (counter.TryGetValue(item, out tempVar))
{
counter[item] += 1;
}
else
{
counter.Add(item, 1);
}
}
//var numberofchars = "";
foreach (KeyValuePair<char, int> item in counter)
{
if (counter.Count > 0)
{
//Label1.Text=split(item.
}
Response.Write(item.Value + " " + item.Key + "<br />");
// Label1.Text=item.Value + " " + item.Key + "<br />";
spnDisplay.InnerText= item.Value + " " + item.Key + "<br />";
}
}
I am trying to make "Hello World" to "World Hello".
But the code is not working properly the way I wanted it to behave.
See the code below:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct llnode
{
char *info;
struct llnode *next;
};
typedef struct llnode NODE;
int main()
{
char msg[50],word[10],*str;
int i=0,length=0,j=0;
NODE *ptr,*front=NULL,*temp,*last=NULL;
//printf("Enter the sentence: ");
str= "Hello World"; //fgets(msg,sizeof(msg),stdin);
while(str[i]!='\0')
{
if((str[i]==' ')||(str[i]=='\n'))
{
word[j]='\0';
j=0;
ptr=(NODE *)malloc(sizeof(NODE));
ptr->info=word;
ptr->next=NULL;
if(front==NULL)
{
front=ptr; // only change the value of front here;
}
else
{
temp=front;
while((temp->next)!=NULL)
{
temp=temp->next;
}
temp->next=ptr;
}
printf("\n##%s\n",front->info); // prints thewords and not
//the first word
}
else
{
word[j]=str[i];
j++;
}
i++;
}
temp=front;
while(temp)
{
length++;
printf("%s ",temp->info);
temp=temp->next;
}
printf("\nLength of Linked List(or, number of words): %d\n",length);
i=0;
printf("\n************************\n");
while(i<length)
{
temp=front;
while(temp->next!=last)
{
temp=temp->next;
}
last=temp;
printf("%s ",temp->info);
i++;
}
return 0;
}
Thanks
There are a number of things wrong with the code:
You are using a single word array to read all the words. So, when you read "Hello", you read into the word array, print "##Hello" and store the pointer to the word array as front->info. Then, you OVERWRITE the word array with World. Also, please note that you NEVER add a node with the word "World" because you exit the loop as soon as you encounter the '\0'. So, your linked list contains only one node. But, there is a problem, since you stored a pointer to the word array in the first node and since the word array has been overwritten with "World", when you exit the loop, there is only one node in the list and the info of this node is word array which contains "World" and not "Hello" like it once did. So, I guess this explains the output?
You should be able to use strtok() for this purpose. See this example, just replace the hashtags with spaces and print backwards. This is by far the easiest way to accomplish this.
Looks like homework... but, for starters, if your delimiters are a space and a newline:
if((str[i]==' ')||(str[i]=='\n'))
...then a string that doesn't contain a space or a newline at the end will never parse the last element:
str= "Hello World"; //fgets(msg,sizeof(msg),stdin);
...so my guess is that you're never even putting "World" into the linked list.
Finally I did this one
/**
I am a boy -> boy a am I
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int i, j, n, temp, temp_i, cnt;
//char *array = "Samsung";
char array[1000];
char newarr[strlen(array)];
printf("Enter The String: \n");
gets(array);
for(i = (strlen(array)-1), n = 0, j = 0; i >= 0; i--)
{
if( array[i] != ' ')
{
n++;
}
else
{
temp = n;
temp_i = i;
for(n = 0; n <= temp; n++)
{
// i = i + 1;
newarr[j++] = array[i++];
}
i = temp_i;
n = 0;
}
if(i == 0)
{
newarr[j++] = ' ';
temp = n;
temp_i = i;
for(n = 0; n <= temp; n++)
{
// i = i + 1;
newarr[j++] = array[i++];
}
i = temp_i;
n = 0;
}
//newarr[j++] = array[i];
}
newarr[j] = '\0';
cnt = 0;
for(j = 0; j <= (strlen(newarr)-1); j++)/*This is not required just do some R n D*/
{
newarr[j] = newarr[++cnt];
}
// printf("The first element is %c \n", newarr[1]);
puts(newarr);
return 0;
}
Here is one solution with c++11 . Which reverses the words as required and prints it on screen.
vector<string> words;
string str = "hello world c++11";
size_t current = 0;
size_t found = str.find(" ");
while(found != string::npos)
{
words.push_back(str.substr(current, found - current));
current = found + 1;
found = str.find(" ",current);
}
words.push_back(str.substr(current));
std::ostream_iterator<string> Display_iter(std::cout," ") ;
std::copy(words.rbegin(), words.rend(), Display_iter);
1) First reverse the entire string ( it gives like "dlrow olleh")
2) and then call/reverse word from first character until space/endOfString encounters.
3) It gives desired output.
#include
#include
int main() {
char *src = "I am a boy";
char dest[50][50];
int idx = 0;
int priv_idx = 0;
int i = 0;
int j = 0;
while(src[i] != '\0') {
if(src[i] == ' ') {
if(priv_idx == idx) {
idx ++;
j = 0;
}
i++;
continue;
}
*(*(dest + idx) + j) = src[i];
i++;
j++;
priv_idx = idx;
}
for (i = idx; i>=0; --i) {
printf("%s\n\r",dest[i]);
}
return 0;
}
#include <stdio.h>
#include <string.h>
#define MAX_ROW 50
#define MAX_COLUMN 50
char dest[MAX_ROW][MAX_COLUMN];
int str_rev_order(char *src)
{
int idx = 0;
int priv_idx = 0;
int i = 0;
int j = 0;
for(i = 0;i<MAX_ROW; ++i) {
memset(dest[i],0,MAX_COLUMN);
}
/* reset the counter */
i = 0;
while(src[i] != '\0') {
if(idx >= MAX_ROW-1) {
printf("Don't support more than %d substring.\n\r",MAX_ROW);
return -1;
}
if(j >= MAX_COLUMN -1) {
printf("Don't support string length more than %d.\n\r",MAX_COLUMN);
return -1;
}
if(src[i] == ' ') {
if(priv_idx == idx) {
/* going to next row & reset the column counter*/
idx ++;
j = 0;
}
i++;
continue;
}
*(*(dest + idx) + j) = src[i];
i++;
j++;
priv_idx = idx;
}
return idx;
}
void print_rev_order(int idx) {
int i;
for (i = idx; i>=0; --i) {
printf("%s\n\r",dest[i]);
}
}
int main() {
char *src = "I am a boy";
int idx = str_rev_order(src);
print_rev_order(idx);
return 0;
}