I currently try to combine 2 arrays without using strncat. The following code doesnt work and the problem lies in one of the for loops. I guess that some of these boundaries are wrong, but I'm not capable of finding the mistake:
#include <stdio.h>
int main() {
char text1[] = {"Hello"};
char text2[] = {", how are you?"};
char result[100];
int count1 = strlen(text1);
int count2 = strlen(text2);
printf("%d\n", count1);
printf("%d\n", count2);
for(int i = 0; i<count1; i++) {
result[i] = text1[i];
}
for(int k = 0; k<count2; k++) {
result[k+1+count1] = text2[k];
}
for(int j = 0; j<count1+count2; j++) {
printf(" %s", result[j]);
}
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char text1[] = "Hello"; //correct way to initialize string
char text2[] = ", how are you?";
char result[100];
int count1 = strlen(text1);
int count2 = strlen(text2);
printf("%d\n", count1);
printf("%d\n", count2);
for(int i = 0; i<count1; i++) {
result[i] = text1[i];
}
for(int k = 0; k<count2; k++) {
result[k+count1] = text2[k]; //k + 1 + count1 causes bug
}
result[count1+count2] = '\0' ; //adding NULL char at the end
printf("%s\n" , result) ; //printing the string using %s
return 0;
}
Instead of defining the size of your result array as 100, you should define it equal to the sum of the length of both the input arrays.
Also, the format specifier should be %c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char text1[] = {"Hello"};
char text2[] = {", how are you?"};
int count1 = strlen(text1);
int count2 = strlen(text2);
char *result = malloc(count1 + count2);
printf("%d\n", count1);
printf("%d\n", count2);
for(int i = 0; i<count1; i++) {
result[i] = text1[i];
}
for (int i = 0; i < count2; i++) {
result[count1 + i] = text2[i];
}
for (int i = 0; i < count1 + count2; i++) {
printf("%c", result[i]);
}
return 0;
}
You do it with fewer variables and a lot less code. You've lost track of what is what and 'skip' a space with 'k+1+count1'... Then try to print, in a loop, characters using a %s format specifier. Too complicated!
#include <stdio.h>
int main() {
char result[100], text1[] = "Hello", text2[] = ", how are you?";
int i = 0, j = 0;
while( (result[ i ] = text1[ i ] ) != '\0' )
i++;
while( (result[ i ] = text2[j++] ) != '\0' )
i++;
puts( result );
return 0;
}
The output is as expected.
So this is the code that works and i've explained each line after the code snippet.
#include <stdio.h>
#include<string.h>
int main() {
char text1[] = "Hello";
char text2[] = ", how are you?";
char result[100];
int count1 = strlen(text1);
int count2 = strlen(text2);
printf("%d\n", count1);
printf("%d\n", count2);
for(int i=0 ; i<(count1+count2); i++){
if(i<count1)
{
result[i]= text1[i];
}
else{
result[i]=text2[i-count1];
}
}
for(int j = 0; j<count1+count2; j++) {
printf("%c", result[j]);
}
return 0;
}
In the first loop, you'd see i'm iterating from 0 to the sum of both the string sizes as i'm assuming that there's a single large string instead of two seperate ones.
As you mentioned that count1 is the size of text1 and count2 as the size of text2, so the logic i used here is that as long as the value of i is lesser than the size of the text1, I'm taking the characters from that position in the text and assigning it to the result string, then once i exceeds that, i'm subtracting the count1 value from the i value as it will again take characters from the 0th position from the text2 and assigning it to the result string.
I would also like to also mention that when you initialise a character array as a string, you just use " ", not {" "} and also when you're printing a character array so you use "%c" not "%s" unless you're printing out a string which you do use "%s" and if so, you can remove the looping statement.
Hope this helps!
Related
I need to split the string of n size and append in an array.
For example:
input:
abcdefghi
4
output:
[abcd,bcde,cdef,defg,efgh,fghi]
My code giving wrong answer:
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "abcdefghi";
char result[100];
for(int i=0;i<strlen(str);i++){
strncat(result, str, str[i]+4);
}
printf("result: %s\n ", result);
}
My output:
abcdefgiabcdefgiabcdefgiabcdefgiabcdefgiabcdefgiabcdefgiabcdefgi
What mistake have I made??
Would you please try the following:
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "abcdefghi";
char result[100];
int n = 4;
int i, j;
char *p = result; // pointer to the string to write the result
*p++ = '['; // left bracket
for (i = 0; i < strlen(str) - n + 1; i++) { // scan over "str"
for (j = i; j < i + n; j++) { // each substrings
*p++ = str[j]; // write the character
}
*p++ = i == strlen(str) - n ? ']' : ','; // write right bracket or a comma
}
*p++ = '\0'; // terminate the string with a null character
printf("result: %s\n", result); // show the result
return 0;
}
Output:
result: [abcd,bcde,cdef,defg,efgh,fghi]
Might this work for you?
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "abcdefghijklmno";
char result[100][100];
int nSplit = 4; //Split size
int nLength = strlen (str); //Lenth of the string
int nTotalString = nLength - nSplit; //total possibilities
int nStrCount = 0;
for (int i = 0; i <= nTotalString ; i ++)
{
for (int j = 0; j < nSplit; j++)
result[nStrCount][j] = str[i + j];
nStrCount++;
}
//print array
printf ("result:[");
for (int k = 0; k < nStrCount; k++)
printf ("\"%s\" ", result[k]);
printf ("]");
return 0;
}
I got given this assignment:
Write a C program that sequentially writes two strings into each other as shown in the figure below. Start with a string
consisting of “X”-es and with each iteration, the first and last X characters must be rewritten until the entire string is
rewritten and the final message is displayed.
Hint: Make use a function in the library, strlen(), to determine the length of a string.
It should output like this:
XXXXXXXXXXXXXXXXXXXXX
IXXXXXXXXXXXXXXXXXXX!
I XXXXXXXXXXXXXXXXXg!
I lXXXXXXXXXXXXXXXng!
I loXXXXXXXXXXXXXing!
I lovXXXXXXXXXXXming!
I loveXXXXXXXXXmming!
I love XXXXXXXamming!
I love CXXXXXramming!
I love C-XXXgramming!
I love C-PXogramming!
I love C-Programming!
Final String= I love C-Programming!
This is what I have so far:
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
//data
char str[] = "I love C-Programming!";
int rows;
int columns;
int length = strlen(str);
int format =5;
//process
{
rows = 0;
while (rows <= length)
{
rows++;
}
while (rows > 0)
{
int count = length;
columns = rows - 1;
while (columns > 0)
{
printf("X");
columns--;
count --;
}
if (rows <= length)
{
printf("%.*s", count, str);
}
printf("\n");
rows-=2;
}
printf("%s", str);
}
//output
printf("\n");
printf("\n");
printf("Final String = %s\n", str);
return 0;
}
It doesn't display properly. Please help!
Thanks.
#include <stdio.h>
#include <string.h>
int main()
{
char s1[] = "XXXXXXXXXXXXXXXXXXXXX";
const char s2[] = "I love C-Programming!";
const int n = strlen(s1);
const int h = n / 2;
int i;
int j;
puts(s1);
for (i = 0, j = n - 1; i <= h; ++i, --j) {
s1[i] = s2[i];
s1[j] = s2[j];
puts(s1);
}
return 0;
}
Hi this is indeed a very simple program. Actually your teacher want you to write a program like below:-
int main(int argc, char **argv)
{
//data
char str1[] = "I love C-Programming!";
char str2[strlen(str1)];
memset(str2, 'X', sizeof(str2));//Set all the character to X
str2[strlen(str1)-1]=0;//end of string character value of '\0'
//int rows;
//int columns;
int length = strlen(str1);
//int format =5;
int i = 0;
int j = length - 1;
do
{
printf("%s\n", str2);//Print the second string first
str2[i]=str1[i];//copy from first character from str1
str2[j]=str1[j];//copy from last character from str1
//so in each iteration we are coping two characters from str1 to str2
}while(i++ != j-- );//once I and j are equal break the loop
printf("%s", str2);
/*
//process
{
rows = 0;
while (rows <= length)
{
rows++;
}
while (rows > 0)
{
int count = length;
columns = rows - 1;
while (columns > 0)
{
printf("X");
columns--;
count --;
}
if (rows <= length)
{
printf("%.*s", count, str);
}
printf("\n");
rows-=2;
}
printf("%s", str);
}
*/
//output
printf("\n");
printf("\n");
printf("Final String = %s\n", str2);
return 0;
}
It will out put like below:-
XXXXXXXXXXXXXXXXXXXX
IXXXXXXXXXXXXXXXXXXX!
I XXXXXXXXXXXXXXXXXg!
I lXXXXXXXXXXXXXXXng!
I loXXXXXXXXXXXXXing!
I lovXXXXXXXXXXXming!
I loveXXXXXXXXXmming!
I love XXXXXXXamming!
I love CXXXXXramming!
I love C-XXXgramming!
I love C-PXogramming!
I love C-Programming!
Final String = I love C-Programming!
If I have a string: char cInputString[] = "Hello World";
And I want to iterate through it and get the ASCII value of each character, how do I write this value to a variable in the code that I can use instead of to the terminal? So on the first pass I have a variable ASCIIValue = 72;
for ( size_t idx = 0; idx < strlen(cInputString); idx++ ) {
printf("ascii of %c = %d \n",cInputString[idx],cInputString[idx]);
}
Variable that you want is asciiValue. Here is your code: (I tested)
#include<stdio.h>
#include <string.h>
int * getASCIIValue(char *array) {
char c;
int i, ascii;
int result[100];
for(i=0; array[i]; i++) {
ascii = (int)array[i];
result[i] = ascii;
}
return result;
}
void main()
{
char cInputString[] = "Hello World";
int asciiValue[100], i;
int *arr = getASCIIValue(cInputString);
for(i=0; i<strlen(cInputString); i++) {
asciiValue[i] = arr[i];
}
for(i=0; i<strlen(cInputString); i++) {
printf("%d", asciiValue[i]);
}
system("pause");
}
The ASCII value would be the value of each character in the string. Simply retrieve them by indexing the string.
for ( unsigned int idx = 0; idx < strlen(cInputString); idx++ ) {
ASCIIValue = cInputString[idx];
}
So I have this caesar cipher program, however when I run it it only prints out numbers instead of the decrypted text. Anyone know what I am missing? I believe there might be something wrong in the bool solved function.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "rotUtils.h"
bool solved( char decodearr[], char dictarr[][30], int size1, int size2){
char* compared;
bool result = false;
for(int j = 0; j < size2; j++){
compared = strstr( decodearr, dictarr[j]);
}
if( compared != '\0'){
result = true;
}
return result;
}
int decode( char codearr[], char dictarr[][30], int size1, int size2)
{
bool solution = false;
int key = -50;
char decodearr[10000];
while(solution == false && key < 51)
{
for( int i = 0; i < size1; i++)
{
if(!isspace(codearr[i]))
{
decodearr[i] = rotate(codearr[i], key);
}
else
decodearr[i] = codearr[i];
}
solution = solved( decodearr, dictarr, size1, size2);
if( solution == false)
{
key++;
}
}
for( int j = 0; j < size1; j++)
{
codearr[j] = decodearr[j];
}
return key;
}
int main( int argc, char* argv[])
{
char* file = argv[1];
char* dictionary = argv[2];
char code[10000];
char dict[30000][30];
FILE* codeFile;
codeFile = fopen(file, "r");
int i = 0;
int j = 0;
int key;
FILE* dictFile;
dictFile = fopen(dictionary, "r");
while(!feof(codeFile))
{
code[i] = fgetc(codeFile);
i++;
}
code[ i + 1] = '\0';
fclose(codeFile);
while(!feof(dictFile))
{
fscanf(dictFile, "%s", dict[j]);
j++;
}
key = decode(code, dict, i, j);
fclose(dictFile);
for(int k = 0; k < i; k++)
{
printf("%d", code[k]);
}
printf( "\nThe key is: %d\n", key);
return 0;
}
printf("%d", code[k]); means "print out the decimal digits that represent the integer code[k]".
If you want "print out the character that represents the integer code[k], then you'd want the %c format specifier instead: printf("%c", code[k]);
You only ever print numbers
printf("%d", code[k]);
perhaps try
printf("%c", code[k]);
which prints the character that number represents.
Just use "%c" instead of "%d" in your code when you want to print code[k].
Good luck!
I'm new to C and am having trouble with strings. What I would like to do is create a string like "val1, val2, val3" in a loop.
Currently my code looks something like:
char tagstr[60] = "";
int k;
int n = 5;
for (k=0; k < n; k++) {
char temp[10] = "";
sprintf(temp, ", val%d", k);
strcat(tagstr, temp);
}
But the output of tagstr is ", val#", where # is some long integer value. I'm guessing I'm doing something wrong with pointers here but I've tried everything I can think of without success... any help would be much appreciated.
EDIT: more context, if it helps:
int tagsClosed = strlen(pch1) - strcspn(pch1, ")");
do {
if (curTag.size > 0) {
// problem section
char tagstr[60] = "";
int k;
for (k = 0; k < 5; k++) {
char temp[10] = "";
sprintf(temp, ", val%i", temp, k);
strcat(tagstr, temp);
}
// This prints out something like ", val-890132840" x 5 (same number)
printf ("String is now: %s\n", tagstr);
}
curTag = *(curTag.parent);
tagsClosed--;
} while (tagsClosed > 0);
curTag is a struct:
typedef struct Tag {
char * name;
int size; // number of children
int tagnum;
struct Tag* parent;
} Tag;
The problem is that sprintf(temp, ", val%i", temp, k); adds the value of temp (which is actually the address of the first character in the array) to the string, and doesn't add the value of k to the string at all. This should be sprintf(temp, ", val%i", k);.
You can calculate the amount of space you'd need in advance (including zero terminator):
5+1 + 5+1 + 5+1 + 5+1 + 5+1 + 1 = 31 characters
Also; using strcat is bad (for performance) because you'd be repeatedly searching for the end of the tagstr and then copying the new characters to the end. It would be better to keep track of the current end of tagstr and store then next group of characters directly at the end with no searching, no temporary string and no copying. For example:
void thing(void) {
char tagstr[60];
int pos = 0;
int k;
int n = 5;
for (k=0; k < n; k++) {
pos += sprintf(&tagstr[pos], ", val%d", k);
}
printf ("String is now: %s\n", tagstr);
}
Works for me:
$ gcc -xc - && ./a.out
int main(void) {
char tagstr[60] = "";
int k;
int n = 5;
for (k=0; k < n; k++) {
char temp[10] = "";
sprintf(temp, ", val%d", k);
strcat(tagstr, temp);
}
printf("[%s]\n", tagstr);
}
[, val0, val1, val2, val3, val4]
Unless you're saying the problem is with the initial ", "..
your temp array is too short!
use
char temp[16];
If you decide you don't want the leading comma and blank, you can use a simple variation on the code you showed:
#include <stdio.h>
#include <string.h>
int main(void)
{
char tagstr[60] = "";
const char *pad = "";
int k;
int n = 5;
for (k = 0; k < n; k++)
{
char temp[10] = "";
snprintf(temp, sizeof(temp), "%sval%d", pad, k);
strcat(tagstr, temp);
pad = ", ";
}
printf("tagstr <<%s>>\n", tagstr);
return 0;
}
The output from the program was:
tagstr <<val0, val1, val2, val3, val4>>
However, your code works correctly for me, albeit with the leading comma and blank.
temp isn't long enough to hold the result of your sprintf. This is exactly why you should use snprintf, strncat and other variants of the string functions that take a size parameter, whenever you can.