I have written the following code to reverse a String. But it is giving some error. It get stuck after calling the reverseStr() function. I am unable to find the bug. Can someone help me?
#include <stdio.h>
#include <stdlib.h>
char * reverseStr(char *str){
int i,len = 0;
while(str[len]!=NULL){
len++;
}
len-=1;char temp;
for(i=0;i<len/2;i++){
//printf("%d %d %s\n",i,len,str);
temp = str[len-i];
str[len-i]=str[i];
str[i]=temp;
//printf("%d %d %s\n",i,len,str);
}
return str;
}
int main(void) {
char *str = "abcdefg";
printf("Original :: %s\n",str);
str = reverseStr(str);
printf("Reversed :: %s",str);
return 0;
}
char *str = "abcdefg";
will place string literal "abcdefg" in the read-only section of the memory and making str to point to that, any writing operation on this memory illegal and hence the runtime error.
Use char str[] = "abcdefg" ; and simply reverseStr(str);
Now you can't do str = reverseStr(str) ; here since types are different, you can store the result in another char pointer though.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reverseStr(char *str){
int i,len;
len = strlen(str);
char temp1,temp2;
int j = len - 1;
for(i=0;i<j/2 + j%2;i++){
printf("%d %d %s\n",i,j,str);
temp1 = str[j-i];
temp2 = str[i];
str[i]=temp1;
str[j-i]=temp2;
printf("%d %d %s\n",i,j,str);
}
return;
}
int main(void) {
char str[10];
strcpy(str,"abcdefgh");
printf("Original :: %s\n",str);
reverseStr(str);
printf("Reversed :: %s",str);
return 0;
}
Related
Here's my code:
#include <stdio.h>
#include <string.h>
char input_buffer[1000];
void get_substring(){
int i;
int length;
printf("Please enter a string:\n");
scanf("%[^\n]s", input_buffer);
printf("Index of first character of substring:\n");
scanf("%d", &i);
printf("Length of substring:\n");
scanf("%d", &length);
printf("Substring is %.*s ", length, input_buffer + i);
}
int main(void) {
// your code goes here
//get_substring(0,4);
get_substring();
return 0;
}
That's my current code, I want to return a pointer of the input, instead of just displaying the substring. Sorry for the confusion everyone.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* getSubstring(char* str,size_t start, size_t length)
{
// determine that we are not out of bounds
if(start + length > strlen(str))
return NULL;
// reserve enough space for the substring
char *subString = malloc(sizeof(char) * length);
// copy data from source string to the destination by incremting the
// position as much as start is giving us
strncpy(subString, str + start, length);
// return the string
return subString;
}
int main(int argc, char* argv[])
{
char *str = "Hallo Welt!";
char *subStr = getSubstring(str,0,20);
if(subStr != NULL)
{
printf("%s\n",subStr);
free(subStr);
}
}
This solution should give you a hint how you would start with such a problem.
My code is giving me a segmentation fault. I'm 99% sure the fault is stemming from my lousy code construction.
#include <stdio.h>
#include <assert.h>
#include <string.h>
int decToBit(unsigned int I, char *str){
str = "";
int currentVal = I;
do{
if(I%2 == 0)
strcat(str,"0");
else
strcat(str,"1");
} while(currentVal > 0);
return(0);
}
You need to make sure that there is enough space in str to add the extra characters:
char myStr[200];
myStr[0] = '\0'; // make sure you start with a "zero length" string.
strcpy(myStr, str);
and then use myStr where you were using str.
As it is, the statement
str="";
points str to a const char* - that is a string you can read but not write.
Incidentally the call signature for main is
int main(int argc, char *argv[])
in other words, you need a pointer to a pointer to char. If I am not mistaken, you would like to do the following (a bit of mind reading here):
Every odd argument gets a 1 added; every even argument gets a 0 added.
If my mind reading trick worked, then you might want to try this:
#include <stdio.h>
#include <string.h>
int main(int argc, char * argv[]) {
char temp[200];
temp[0] = '\0';
int ii;
for(ii = 0; ii < argc; ii++) {
strncpy(temp, argv[ii], 200); // safe copy
if(ii%2==0) {
strcat(temp, "0");
}
else {
strcat(temp, "1");
}
printf("%s\n", temp);
}
}
edit just realized you edited the question and now your purpose is much clearer.
Modified your function a bit:
int decToBit(unsigned int I, char *str){
str[0] = '\0';
char *digit;
do
{
digit = "1";
if ( I%2 == 0) digit = "0";
strcat(str, digit);
I>>=1;
} while (I != 0);
return(0);
}
It seems to work...
In do-while loop you should increment the value of currentVal. Otherwise it will be an infinity loop and you will end up with Segmentation fault.
Initialize str[0] properly.
Divide I by 2 each loop.
But then the string will be in a little endian order. Doubt that was intended?
int decToBit(unsigned int I, char *str) {
str[0] = '\0';
do {
if (I%2 == 0)
strcat(str,"0");
else
strcat(str,"1");
I /= 2;
} while(I > 0);
return(0);
}
// call example
char buf[sizeof(unsigned)*CHAR_BIT + 1];
decToBit(1234567u, buf);
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <assert.h>
char *decToBit(unsigned int I, char *str){
int bit_size = CHAR_BIT * sizeof(I);
str += bit_size;
*str = 0;
do{
*--str = "01"[I & 1];
}while(I>>=1);
return str;
}
int main(){
char bits[33];
printf("%s\n", decToBit(0, bits));
printf("%s\n", decToBit(-1, bits));
printf("%s\n", decToBit(5, bits));
return 0;
}
If given the following char prose:
"Hope is the thing with feathers
That perches in the soul
And sings the tune without the words
And never stops at all”
How do I count the length of the string and number of spaces? Here is what I have thus far:
#include <stdio.h>
#include <ctype.h>
int count(char *string);
int main(void){
char prose[ ] =
"Hope is the thing with white feathers\n"
"That perches in the soul.\n"
"And sings the tne without the words\n"
"And never stops at all.";
printf("count of word : %d\n", count(&prose[0]));
return 0;
}
char *NextWordTop(char *string){
static char *p = NULL;
char *ret;
if(string)
p = string;
else if(!p)
return NULL;
while(isspace(*p))++p;
if(*p){
ret = p;
while(!isspace(*p))++p;
} else
ret = p = NULL;
return ret;
}
int count(char *str){
int c = 0;
char *p;
for(p=NextWordTop(str); p ; p=NextWordTop(NULL))
++c;
return c;
}
#include <stdio.h>
#include <ctype.h>
int main(void){
char prose[ ] =
"Hope is the thing with white feathers\n"
"That perches in the soul.\n"
"And sings the tne without the words\n"
"And never stops at all.";
int len, spc;
char *p = prose;
for(len=spc=0;*p;++p){
++len;
if(isspace(*p))//if(' ' == *p)
++spc;
}
printf("length : %d\t spaces : %d\n", len, spc);
//length : 123 spaces : 23
return 0;
}
Well, the title already says what I need. I tried to use a loop but it didn't go well, so, I came for your help guys!
Here's my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char word[31], word2[31];
int size1, size2;
int i, j, k; // control
int count = 0;
printf ("\nInput the first word");
scanf ("%s", word);
printf ("\nInput the second word: ");
scanf (" %s", word2);
// I tried to make a loop through the first string and if it matches a letter, it would loop through the others (if they are equal, we have a substring), but failed to put it on the `for` loop
printf ("'%s' appears %d times within '%s'", word2, count, word);
return 0;
}
strstr is a useful function, it shortens your code considerably; when you find a match, just try again with the rest of the string;
#include <string.h>
#include <stdio.h>
int main()
{
const char* source = "aabaa";
const char* string2find = "aa";
int occurrences;
const char *ptr, *lastfind = NULL;
for(ptr=source; (lastfind=strstr(ptr, string2find)); ptr=lastfind+1)
occurrences++;
printf("%d\n", occurrences);
return 0;
}
...or if you're really set on doing it without string.h functions, the code gets a bit more verbose;
#include <string.h>
#include <stdio.h>
int main()
{
const char* source = "aaabaa";
const char* string2find = "aa";
int count=0;
const char *position;
for(position=source; *position; position++) {
int comparepos, equal=1;
for(comparepos=0; string2find[comparepos]; comparepos++) {
if(position[comparepos] != string2find[comparepos]) {
equal = 0;
break;
}
}
count+=equal;
}
printf("%d\n", count);
return 0;
}
Use strstr to find occurence of string in other string:
#include <stdio.h>
#include <string.h>
int main () {
char* a = "aaaa";
char* b = "aa";
char* c;
int count = 0;
for(c = a; *c; c++){
if(strstr(c, b)){
count++;
}
}
printf("count %d\n", count);
}
Also, use strlen to find length of a string..
Here is a program to accept a:
Sentence from a user.
Word from a user.
How do I find the position of the word entered in the sentence?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char sntnc[50], word[50], *ptr[50];
int pos;
puts("\nEnter a sentence");
gets(sntnc);
fflush(stdin);
puts("\nEnter a word");
gets(word);
fflush(stdin);
ptr=strstr(sntnc,word);
//how do I find out at what position the word occurs in the sentence?
//Following is the required output
printf("The word starts at position #%d", pos);
return 0;
}
The ptr pointer will point to the beginning of word, so you can just subtract the location of the sentence pointer, sntnc, from it:
pos = ptr - sntnc;
Just for reference:
char saux[] = "this is a string, try to search_this here";
int dlenstr = strlen(saux);
if (dlenstr > 0)
{
char *pfound = strstr(saux, "search_this"); //pointer to the first character found 's' in the string saux
if (pfound != NULL)
{
int dposfound = int (pfound - saux); //saux is already pointing to the first string character 't'.
}
}
The return of strstr() is a pointer to the first occurence of your "word", so
pos=ptr-sntc;
This only works because sntc and ptr are pointers to the same string. To clarify when I say occurence it is the position of the first matching char when the matching string is found within your target string.
You can use this simple strpos modification
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int strpos(char *haystack, char *needle, int offset);
int main()
{
char *p = "Hello there all y'al, hope that you are all well";
int pos = strpos(p, "all", 0);
printf("First all at : %d\n", pos);
pos = strpos(p, "all", 10);
printf("Second all at : %d\n", pos);
}
int strpos(char *hay, char *needle, int offset)
{
char haystack[strlen(hay)];
strncpy(haystack, hay+offset, strlen(hay)-offset);
char *p = strstr(haystack, needle);
if (p)
return p - haystack+offset;
return -1;
}
For some reasons I was having trouble with strstr(), and I also wanted index.
I made this function to find the position of substring inside a bigger string (if exists) otherwise return -1.
int isSubstring(char * haystack, char * needle) {
int i = 0;
int d = 0;
if (strlen(haystack) >= strlen(needle)) {
for (i = strlen(haystack) - strlen(needle); i >= 0; i--) {
int found = 1; //assume we found (wanted to use boolean)
for (d = 0; d < strlen(needle); d++) {
if (haystack[i + d] != needle[d]) {
found = 0;
break;
}
}
if (found == 1) {
return i;
}
}
return -1;
} else {
//fprintf(stdout, "haystack smaller\n");
}
}
My comment to the ORIGINAL post in this thread:
This declaration is INCORRECT:
char sntnc[50], word[50], *ptr[50];
C code would not even compile : it will fail on this line:
ptr = strstr(sntnc,word);
So the line shall be changed to :
char sntnc[50], word[50], *ptr;
And you do NOT need memeory allocated to 'ptr string'. You just need a pointer to char.