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 1 year ago.
Improve this question
Can anyone please help me.I want to remove character from char* in C.
For example, char *str this str equals to "apple" and first i remove 1. character and define a new variable then remove 2. character and define new variable and so on until the str ends.
How can ı do that ? I'm completely new to C, and just can't seem to figure it out
Assuming you only need to remove characters from the left.
Because strings in C are arrays of characters, and arrays are pointers to the first element of the array, you can create variables that point to specific indices in you original char array.
For example
char* myString = "apple";
char* subString = myString+1;
printf("%s\n%s\n", myString, substring);
would produce the output
apple
pple
We could generalize this to store all substrings obtained by removing characters from the left in an array of char* pointers (pointers to pointers). Like so:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char** GetSubStrings(char* input)
{
int length = strlen(input);
char** result = calloc(length, sizeof(char*));
for(int i = 0; i < length; i++)
{
result[i] = input + i;
}
return result;
}
int main()
{
char* myString = "apple";
char** subStrings = GetSubStrings(myString);
for(int i = 0; i < strlen(myString); i++)
{
printf("%s\n", subStrings[i]);
}
free(subStrings);
return 0;
}
Related
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 10 months ago.
Improve this question
For a school assignment, I am to Create variables in main() that will store the counts and pass pointers to these variables to your functions so that the functions can modify the variables via the pointers. This is a school assignment so rather than someone Give me the answer, I would prefer is someone could help point me in the right direction of using pointers. The Code does work, but not in the way I would like yet.
the code is as follows
void myFunction(int *letters, int *numbers, int *otherCharacters){
}
int main(int argc, char * argv[]) {
// Code for command line argument
if (argc == 2) {
int letters = 0;
int numbers = 0;
int otherCharacters = 0;
int totalCharacters;
int length = strlen(argv[1]);
for (int i = 0; i < length; ++i){
if (isalpha(argv[1][i]) != 0)
++letters;
if (isdigit(argv[1][i]) != 0)
++numbers;
if (isdigit(argv[1][i]) == 0 && isalpha(argv[1][i]) == 0)
++otherCharacters;
}
totalCharacters = letters + numbers + otherCharacters;
printf("%i letters\n%i digits \n%i other characters\n%i characters total\n", letters, numbers, otherCharacters, totalCharacters);
}
I am hoping to rather than change the values of letters, numbers, otherCharacters, and totalCharacters in the main function use pointers to do so in myFunction(). any help on how to use pointers to do so would be much appreciated. Again, I am not asking for an answer, as I would like to complete this assignment myself.
Seems like the function is supposed to look at a string and tell you how many letters, numbers, and other characters there are. It needs to take the counts as pointers, and the string.
void countCharacters(const char *string, int *letters, int *numbers, int *other) {
....
}
Because they are pointers, when incrementing them you need to dereference them first to get their values. Instead of letters++ it would be (*letters)++.
And we can replace the main code to show how you'd call this.
int main(int argc, char * argv[]) {
// Exit early to avoid deeply nesting all the code.
if (argc != 2) {
perror("please supply a string");
return 1;
}
int letters = 0;
int numbers = 0;
int other = 0;
// Pass in the string (already a pointer) and the counts as pointers.
countCharacters(argv[1], &letters, &numbers, &other);
int total = letters + numbers + other;
printf("%i letters\n%i digits \n%i other characters\n%i characters total\n", letters, numbers, other, total);
}
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 1 year ago.
Improve this question
I'm trying to print random words with the use of rand().
I think that I've made a mistake on the pointer arithmetic since I get a weird output.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main ()
{
srand(time(0));
const int randomBit = rand() % 2;
char * sz[] ={"good", "bad"};
switch (randomBit)
{
case 0:
for (char *i=*sz; *i<(sz+3); i++)
{
printf("%c", *i);
}
break;
case 1:
for (char *i=*(sz+3); *i!=0x0; i++)
{
printf("%c", *i);
}
break;
default:
break;
}
return 0;
}
What's my mistake?
Thank you.
Given this declaration ...
char * sz[] ={"good", "bad"};
... this code has undefined behavior:
for (char *i=*(sz+3); *i!=0x0; i++)
The expression *(sz+3) is equivalent to sz[3], but array sz has only two elements, so the maximum index is 1.
Likewise, the expression *sz is equivalent to sz[0]. That one is semantically ok but stylistically poor. Likewise stylistically poor is splitting out two separate cases when you could instead cover both with the same code by using sz[randomBit] to select which string to print.
Furthermore, it is unclear why you are printing character by character. Perhaps that's part of the assignment, but in the real world a programmer would probably write ...
printf("%s", sz[randomBit]);
... instead of that entire switch statement.
Your code is incredibly complicated (and wrong).
What's wrong with this:
int main()
{
srand(time(0));
const int randomBit = rand() % 2;
char* sz[] = { "good", "bad" };
printf("%s\n", sz[randomBit]);
return 0;
}
or if you are not allowed to use the %s format specifier as part of your assignement:
for (char* i = sz[randomBit]; *i != 0; i++)
{
printf("%c", *i); // or putchar(*i);
}
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
I'm trying to write a function, that deletes each character in s1, that matches any character in the string s2.
#include <stdio.h>
#include <string.h>
void squeeze(char s1[], char s2[])
{
int i1, i2, j, contains_char;
for(i1 = j = 0; s1[i1] != '\0'; ++i1){
contains_char = 0;
for(i2 = 0; s2[i2] != '\0'; ++i2)
contains_char += s1[i1] == s2[i2];
if(!contains_char)
s1[j++] = s1[i1];
}
s1[j] = '\0';
}
int main()
{
char test[5] = "Test";
char x[2] = "et";
squeeze(test, x);
printf("%s", test);
}
But when running the code it prints nothing. When i debugged it in gdb i found out that the variable s2 in squeeze contains the string "etTest".
Can someone tell me why this is happening ?
Your variable s2 is not containing "etTest". It`s just your 2 variable (s1 and s2), storing in one memory location in stack. (comments about s2[3] is right )
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
So I've got a problem with int and string in C.
My task is to write a function that will output the error rate in string.
For example if the string is "aaabbbcccdxm" then the output should be "1/12".
By "error" I mean any letter from n to z, and any letter from a to m is "good".
I thought that I could do it by using a for loop to check every letter in the string, and then if to add value to int error which would be numbers of bad letters, but I don't know how to convert that "int error" value to string with output error value/string dimension. Any ideas?
You can use printf to format your output. I recommend reading the man 3 printf on a linux machine or from google.
Here is what such a program could look like:
#include <stdio.h>
#include <string.h>
int main()
{
const char * input_str = "aaabbbcccdxm";
int size = strlen(input_str);
int error = 0;
for (int i = 0; i < size; ++i)
{
if (input_str[i] >= 'n')
error++;
}
printf("%d/%d\n", error, size);
return 0;
}
size_t errors(const char *str, const char *legal)
{
size_t errcnt = 0;
while(str && *str)
{
errcnt += !strchr(legal, *str++);
}
return errcnt;
}
int main()
{
char *str = "aaabbbcccdxm";
printf("%zu/%zu\n", errors(str,"abcdefghijklm"), strlen(str));
return 0;
}
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 4 years ago.
Improve this question
I've got string as follows
"123 132 244" where that max value for an entry is 255
how can i convert that string to
unsigned char arr[3] = [123, ,132, ,244]
Step 1 : valid the string's format (number - one space - number - one
space ...)
Step 2 : Count the number of space
Step 3 : Allocate the final array
Step 4 : use strtok to have token + sscanf to convert the string to number
Step 5 : return array (+ array size ? It's always useful).
In which step do you have difficulty ?
The expression "123 132 244" is a string literal. If you have access to string functions such as strtok() (defined in strings.h) then parse the string into three char values using strtok() and a string converter such as atoi() or strtol(). If you do not have access to strings.h, then the string to unsigned char conversion will need to be done another way. Here is one example:
const char str[] = {"123 132 244"};
void convertStr(const char *string, unsigned int ucArr[3], size_t size);
int main(void)
{
unsigned int ucArray[3];
convertStr(str, ucArray, sizeof(str)/sizeof(str[0]));
return 0;
}
void convertStr(const char *string, unsigned int ucArr[3], size_t size)
{
int i=0, j=0, k=0;
int accum[3] = {0};//store numeric version of 3 alpha characters
int ex = 0;//use in conversion of single digit value to place value.
int acm = 0;//accumulate integer value of 3 successive integer values
//stored in accum
while(1)
{
if(isdigit(*string))
{
accum[i] = *string - '0';
i++;
}
else
{
//convert
for(k=i-1;k>=0;k--)
{
ex = pow(10, k);
acm += accum[i-k-1]*ex;
}
ucArr[j] = acm;
j++;
i=0;
}
acm = 0;
if(*string == NULL) break;
*string++;
}
}