Title | CZ1003 Tutorial 4 - Character Strings in c programming |
---|---|
Author | Aloysius Tan |
Course | Introduction To Computational Thinking |
Institution | Nanyang Technological University |
Pages | 3 |
File Size | 121.5 KB |
File Type | |
Total Downloads | 82 |
Total Views | 142 |
CZ1003 Tutorial 4 - Character Strings in c programming
String declaration, initialization, and operations
string input and output
string function
ctyphe.h character function
string to number conversion
formatted string i/o
Array of character strings...
Tutorial4–CharacterStrings 1. Whatdoesthefollowingprogramprint? #include #include #defineM1“Howareya,sweetie?” charM2[40]=“Beattheclock.”; char*M3=“chat”; intmain() { charwords[80],*p; printf(M1); puts(M1); puts(M2); puts(M2+1); fgets(words,80,stdin); /*userinputs:winatoy.*/ if(p=strchr(words,'\n'))*p='\0'; puts(words); scanf(“%s”,words+6); /*userinputs:snoopy.*/ puts(words); words[3]=‘\0’; puts(words); while(*M3)puts(M3++); puts(‐‐M3); puts(‐‐M3); M3=M1; puts(M3); return0; } 2. The following unknown function receives a string argument and a character argument, modifies the string argument and returns an integer value. Describe the purpose of the function.Giveanexampletosupportyouranswer. intunknown(charstr[],charc) { intx,y=0,z=0; for(x=0;str[x]!=‘\0’;x++) if(str[x]!=c) str[y++]=str[x]; else z++; str[y]=‘\0’; returnz;
Page 1
} 3. Writethefunctionstrncpy()thatcopiesnotmorethanncharacters(charactersthatfollowa null characterare notcopied)fromthe arraypointedtobys2 to the arraypointedtobys1. If the array pointed to by s2 is a string shorter than n characters, null characters are appended to the copy in the array pointed to by s1, until n characters in all have been written.Thestrncpyreturnsthevalueofs1.Thefunctionprototypeis:
char*strncpy(char*s1,char*s2,intn);
WriteaCprogramtotestthefunction. Somesampleinputandoutputsessionsaregivenbelow: (1)TestCase1 Enterthestring: Iamaboy. Enterthenumberofcharacters: 7 stringncpy():Iama (2)TestCase2 Enterthestring: Iamaboy. Enterthenumberofcharacters: 21 stringncpy():Iamaboy. 4. WriteaCfunctionthatcomparesthestringpointedtobys1tothestringpointedtobys2.If thestring pointedtobys1isgreaterthan, equalto,orlessthanthestring pointedtobys2, then it returns 1, 0 or –1 respectively. Write the code for the function without using the standardCstringlibraryfunctionstrcmp().Thefunctionprototypeisgivenasfollows:
intstringcmp(char*s1,char*s2); WriteaCprogramtotestthefunction. Somesampleinputandoutputsessionsaregivenbelow: (1) TestCase1: Enterasourcestring:abc Enteratargetstring:abc stringcmp():equal (2) TestCase2: Enterasourcestring:abcdefg Enteratargetstring:abcde123 stringcmp():greaterthan (3) TestCase3: Enterasourcestring:abc123 Enteratargetstring:abcdef stringcmp():lessthan (4) TestCase4: Enterasourcestring:abcdef Enteratargetstring:abcdefg
Page 2
stringcmp():lessthan
Page 3...