how can I multiply strings in C like I do in python? - c

in python you can easily type:
str = "hi"
print(str * 10)
and the output would be hi printed 10 times. I'm currently learning how to code in C and I have to do this. Can someone teach me how I can do this kind of thing in C? Thanks in advance

Use for() loop:
Example:
#include <stdio.h>
int main() {
char* str = "hi";
for (int i = 0; i < 10; ++i) {
printf("%s", str);
}
}
And if you need to actually multiply the string (not just print n times) you can use the following mulstr(), just don't forget to test for NULL and to free():
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <error.h>
char* mulstr(char* str, size_t i) {
size_t len = strlen(str);
char* newstr = malloc(len * i + 1);
if (newstr) {
char* writer = newstr;
for (; i; --i) {
memcpy(writer, str, len);
writer += len;
}
*writer = 0;
} else {
perror("malloc");
}
return newstr;
}
int main() {
char* str = "hi";
char* newstr = mulstr(str, 10);
if (newstr) {
printf("%s", newstr);
free(newstr);
}
}

Using for-loop is the best way to implement this.
You can just create a customized print function which will do the same thing as python does. I am just giving a prototype here.
#include <stdio.h>
void print(char *string,int n)
{
int i;
for(i=0;i<n;i++)
{
printf("%s\n",string);
}
}
int main()
{
char *str="Hi";
print(str,2);
return 0;
}
Here second argument in the function n will tell you how many times you want to print the string.
The output will look like
Hi
Hi

Related

Duplicate function -> exited, segmentation fault ç_ç

I'm programming in C, I know why when I start my program, the terminal show me this error, but I don't know how to fix it (I have read many question about this, but no I can't solve this problem) :
My function is :
char * String_dup(char const string[]) {
size_t size = strlen(string);
char * copy = malloc(size * copy[0]);
assert(copy != NULL);
strcpy(copy, string);
return copy;
}
it consist to duplicate my string[].
And this is my test :
void StringTest_dup(void) {
char string[] = "voiture";
assert(strcmp(string, String_dup(string)));
}
Thank you for your help.
I re-wrote it a bit and it seems to work without a problem. One obvious misundertanding you have is that strcmp returns 1 when they match which is wrong. If the two inputs to strcmp are the same then it returns 0, thus !strcmp(...).
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
char* String_dup(const char* string) {
size_t size = strlen(string);
char* copy = malloc(size * sizeof(char) + 1);
assert(copy != NULL);
strcpy(copy, string);
return copy;
}
int main(void) {
const char* string = "test";
char* copy = String_dup(string);
assert(!strcmp(string, copy));
printf("%s\n", string);
printf("%s\n", copy);
free(copy);
return 0;
}

Print function print some strange chars

i'm trying to create a random strings using this function:
static char *rand_string(char *str)
{
const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJK";
int i;
for ( i = 0; i < 10; i++)
{
int key = rand() % (int) (sizeof charset - 1);
str[i] = charset[key];
}
str[11] = '\0';
return str;
}
The problem is this: sometimes when i am going to print the pointer, it display some strange char like this:
As you can see in the first launch the chars in a string are 10, in the second and third launch the chars in a string are 11...
This is my program:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
static char *rand_string(char *str);
int main()
{
char *string, //str
*string_result; //str1
int dimensione= 15,
i;
for(i=0;i<dimensione;i++)
{
string_result = rand_string(string);
printf("%s\n", string_result);
}
}
static char *rand_string(char *str)
{
const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJK";
int i;
for ( i = 0; i < 10; i++)
{
int key = rand() % (int) (sizeof charset - 1);
str[i] = charset[key];
}
str[11] = '\0';
return str;
}
You can view and test my code here --> https://onlinegdb.com/r1yY8DWc8
Your whole code invoke undefined behavior, because you are passing string which is an uninitialized pointer which may "not" be guaranteed to accessible for the 11 bytes your are accessing in the rand_string() function.
You need to allocate memory from the main() and pass that buffer to be filled by the random string generator function, that way you have control of the memory you are modifying.
Also the for loop in your generator already fills indices from 0 to 9. To set the final byte to NULL, you need to use the index as 10.
Also the headers time.h and unistd.h are useless here. Here is a re-write of the same program with memory allocated through malloc(). Also modified your function rand_string() to void instead of returning a string.
#include <stdio.h>
#include <stdlib.h>
void rand_string(char *str);
int main()
{
int dimensione= 15;
char *string = malloc(11 * sizeof *string); // extra byte for NULL
if (!string) return 1;
int i;
for(i=0;i<dimensione;i++)
{
rand_string(string);
printf("%s\n", string);
}
free(string);
return 0;
}
void rand_string(char *str)
{
const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJK";
int i;
for ( i = 0; i < 10; i++)
{
int key = rand() % (int) (sizeof charset - 1);
str[i] = charset[key];
}
str[10] = '\0';
}
Always compile with extra flags to enable all sorts of warnings from your compiler. For e.g. with gcc always add -Wall -Wextra to see the warnings that you could fix from your side.

how to reverse a string using array of pointers?

I want to reverse a string(user gives at runtime) using array of pointers,malloc and not by using array of characters. Can anybody help me by giving me a code? I am very new to C. Thanks in advance.
I am not sure what you are asking, But the following program meets your conditions,
1. there is array of pointers
2. there is malloc
3. there is no character array
#include <stdio.h>
#include <stdlib.h>
#define STR_MAX_SIZE 256
int main()
{
char *str;
char *pos[2];
char c;
if((str = malloc(STR_MAX_SIZE)) ==NULL) {
return -1;
}
scanf("%s",str);
pos[0] = str;
pos[1] = str;
while(*pos[1]) {
pos[1]++;
}
pos[1] -= 1;
while(pos[0] < pos[1]) {
c = *pos[0];
*pos[0] = *pos[1];
*pos[1] = c;
pos[0]++;
pos[1]--;
}
printf("reversed : %s\n",str);
return 0;
}

Null terminating char pointer

I am completely newbie in C.
I am trying to do simple C function that will split string (char array).
The following code doesn't work properly because I don't know how to terminate char array in the array. There are to char pointers passed in function. One containing original constant char array to be split and other pointer is multidimensional array that will store each split part in separate char array.
Doing the function I encountered obviously lots of hustle, mainly due to my lack of C experience.
I think what I cannot achieve in this function is terminating individual array with '\0'.
Here is the code:
void splitNameCode(char *code, char *output);
void splitNameCode(char *code, char *output){
int OS = 0; //output string number
int loop;
size_t s = 1;
for (loop = 0; code[loop]; loop++){
if (code[loop] == ':'){
output[OS] = '\0'; // I want to terminate each array in the array
OS ++;
}else {
if (!output[OS]) {
strncpy(&output[OS], &code[loop], s);
}else {
strncat(&output[OS], &code[loop], s);
}
}
}
}
int main (int argc, const char * argv[]) {
char output[3][15];
char str[] = "andy:james:john:amy";
splitNameCode(str, *output);
for (int loop = 0; loop<4; loop++) {
printf("%s\n", output[loop]);
}
return 0;
}
Here is a working program for you. Let me know if you need any explanation.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
void splitNameCode(char *code, char **output) {
int i = 0;
char* token = strtok(code, ":");
while (token != NULL) {
output[i++] = token;
token = strtok(NULL, ":");
}
}
int main (int argc, const char *argv[]) {
char* output[4];
char input[] = "andy:james:john:amy";
splitNameCode(input, output);
for (int i = 0; i < 4; i++) {
printf("%s\n", output[i]);
}
return 0;
}
If I understand your intent correctly, you are trying to take a string like andy:james:john:amy and arrive at andy\0james\0john\0amy. If this is the case, then your code can be simplified significantly:
void splitNameCode(char *code, char *output){
int loop;
strncpy(code, output, strlen(code));
for (loop = 0; output[loop]; loop++){
if (output[loop] == ':'){
output[loop] = '\0'; // I want to terminate each array in the array
}
}
}

Why does this program give segmentation fault?

It's a beginners question: Why is this breaking/giving an error?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strtrim_right(char *p)
{
char *end;
int len;
len = strlen( p);
while (*p && len)
{
end = p + len-1;
if(isalpha(*end))
*end =0;
else
break;
}
return(p);
}
int main ()
{
char *x="PM123BFD";
strtrim_right(x);
printf("%s", x);
return 0;
}
Change
char *x="PM123BFD";
to
char x[]="PM123BFD";
You cannot modify a string literal, so instead pass the function a char array which it can modify.
I don’t see why it should break – I would rather expect an infinite loop: the while condition will always be true and the loop will never be left.
Rework the loop condition, it’s borked. Then look at the variables you have: you never change the values of either p or len. This isn’t right. Furthermore, the code inside the loop is much more complicated than need be. Think about whether you really need three variables here.
Ok thanks to the 2 answers above here is what seems to be ok now:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strtrim_right(char *p)
{
char *end;
int len;
len = strlen( p);
while (*p && len)
{
end = p + len-1;
if(isalpha(*end))
*end =0;
else
break;
len = strlen(p);
}
return(p);
}
int main ()
{
char x[]="PM123BFD";
strtrim_right(x);
printf("%s", x);
return 0;
}

Resources