KEMBAR78
Strings | PDF | Computer Programming | Character Encoding
0% found this document useful (0 votes)
21 views25 pages

Strings

Uploaded by

mahanoct1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views25 pages

Strings

Uploaded by

mahanoct1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Ctring

appliralie ni Surh at craing, inaerting,pial


ttit'nq
clata
i starch o po diu lar
p i n oihin a tegt, de(ete d, platt h
anolher ptern.

Array, this tnt at at ter


-I ha rater a ray. k*.

tharaitr oray
Ne
drloring
sable rhaaters narly L, L, L, and 0. p
he
Ifese horartrs o null thavater ('\a)is cdhrod

leacing
f we clast a cting by riding
har str fro];
hen c4r can be vcncd by niinq
Stant funtione

1>using qt ehar), get ch)


entedly.
Ctr2I
tan be cd usincq seanto by iting
Scanf (" . S", St r);
N\ain drawbac th at Scanf in strings t monint
pae is entountered, ke string itoumita
by te scanf ) fundion.
Unlike in f.d), flat (1-4)
ind) s fos mat does not
Cqive ampersand befese the variablk name.
iy Tfe n t method t reading a string is by sing
pts) funtion. The at ing can b neacl by oriting
qets()
gets ktr);
is a simple funtion that ovc rcomes he
drawbche of the san f() ofune tion. The qets ()
fun cton takiy he sthr ting actdrem of the ctring
whith wiI| hold e input.
a g
-The string inputte nul i
wtiny,¿haracte.
geta) aueto matialy
termintacdh a
can alo be eael by calling the qtihart)
iiString
function rptatelly do Tad a sLquenu of cingle
charas (unls derminatine tharatkr is ontredl)
lan be olisplayed on seren ging 3 waye.
is Using prif0 funetin.
> ting puts)funtion.
i> usinn purt ehar () funedion vepeadndly
busin prrdfo funtien
A striny ton be digayed wing prntfl) by oriting

n>uiny puts() funion. - The nezt mhecl if noritr


striny 3 by wsing puts() fundion. the string ea
be displayed by roriting
putsor;
is a simple funtion that Overtomut -he
draw backs of the printfo funtion.
iiiy Sting Can abo be wrtten by taling h ptharly
funtion repatelly do print a uquent of Cinrle
harats.
eharato
Summary ot tuntions wsecd to reasl ane nrde
Funtion lperethion,
> get char ) Dsed to yeuel a ehareeter tom e
Keybo ar el: dnis tavtige vedurn.
I4 antas returte an inteer,in shieh
h lo oreur bye tontins the charatr.
getchar() ean be ied to input any bey
inelu dina Ketern, "ab anel Æsc.
Funtion oparadion.
7t eh) Is an alHernatie tr tehar(). Unbte
tuntion raits
ptuhar), the qetchur) hich
after it rturns
immediaely
getehe ) Sinilar to qetehe).Th only obfferent
s hat
screen.
putchar') Uhed to write a tharatir to tke kereen.
t aupts en inte ger paramitr bf which
ony t lavd-oreer byte iu otpt to te
Bureen.

>write a proyam doto odiaplay a string using prinf)


* inelue <stoio.h
+ inelude <eonioh>
int mon C)
Lehar atrl] "ntaductin to c';
elrserc);
printf("n }2s1, str);
rintf l2os I", Str); et ch );
Teturn 0;
print(\n l -20s} str);
printfr"\n l .4s]} tr);
printf ("\n 20, 4s| str);
printf(\n l% -20. 45str);
Intocuetin to c)
Jntrodutiun to I
| Iotrlucton to c

atrl

rite to print a ollhniny patder.

H
H L
HE L L

H L LD
H1 LL

indu ce <stdo. h>


--inlude <ton'o. h>
int maun ()
tot i, n, P}
char sr[] = "HELLO";
prindf ("n");
doy i 0; i<5j i++)
r2s
P: i+ 1 ;
P str);

rintf ("\n -s. +s" p, s+r);


qet ch();
yeturn 0;

SprintfOfuncton.
the ibrory function sprint{0 8 Aimilar to
printg(?
The only dieeou u that the fomat ted oudpt
han doretly
K nir tten to on mmmory area raher
do n stondard oudput (ureen).
Sprintf() is usetud in Siduatinsdrnnsmit4el
when ornatted
ver
mmmery have do be
sdring in channel e de a Speitl aua.
tonmuniation

Sprint{ (char t butfer, ton st char * fornat [ arqimud


iat
J);
Peressing Znpad. Str26

Th Scan f() funton be wel do reacl a helel


rithout cnsiygi to Voniable.
Tha is elon by preecling fat feld's tormat codle
Seant ("% d tet.d, hr, 4min);
-The tim Lan be reacd as a: os. Hee -R colon
ioud be wend but not aigred to ony ting
Scanst
Scanset s wed do dafne a Bet of charatrs
hich muy be rudad and auiyned to th corrspaning
gtring
Seansetis dutineel by pauing. fe charatvs
insicle square brauheto prifaed oith a 9.. Lhe

Cocle:
#inlude <steio. h
int motnl)
char etrCio]
printf ("\n Enter string:":
Seant (" [oeiou, str)
ritf(" vh strina : .s,st);
-The ocle ollstp epdna a charatr
as the user ents a haracr Aat s not a vowel.
- t the tirt harat in the ket is a ^ Caret sym)
hen sant ) nill atcupt any eharatv Rat s not
ouonedl by e scantt. Lue.
Sanf ("3. [^acouJ",s4rd;
SSant () funtion.
The ssanf funtion aeepts a strinq -from nhich
to rea input.
- lt aepts a tenlali
templae string and o keris of
rlated arqumand
--the sscant functon Bimar to seant tunton
enupt thut tRe chra t arqumunt of sseanf spripy
a string- from nheh to ad, whereasfcant Car
ony vead trom stonalaal int.
ssant (onst ehar *tr, onst chartfrrd.
[p1, p2 ...);
Here cs cantt) reudy data fom str andt &
toreg
fen ao rbing do tfe paramit frmat into the
lecations given by ke additional argunnti.
ilhe
Ss cant (str, "-",num)
Here ,ss cant tae hes 3
etr2g
Strhat tondains dote to be eon verted.
frrmat spoite r
-Seeond &a string conthining aconvertec.
dfat detminas how thi trinn result
the hird s a memory Locaton to pdaehe reg
ot the tonvers ion.
SAring Tasconomy
tring atfr in txd lanth
frmat or in varabl hngth fmat
(Stringy
Voyria bu
Fized
leng th legyh
foeimited
lControll

Fixd lenyth string:.


wen storin a string tna dxd angth toranat,
you nud to speuty ofo
tke striny Variabu,.
-If the sice is too mal, in you nill not be ablu
.store al thu e n in e stringe. On the
handithi string size is
memory pae iawll be nate
Large, unne(sanl
Voriable lenth trinys
-A beter option is to a voriable Lenqth fomat
in whih theâ striny tan be panekel
to actomecali ha eement in it.
ng th tonta led edrings
bngth ton tro leel string you necd o peuty
the humber ot ehotrs in The
Count wed by sdring manipatioo untion to
wsed
cetemine tke adallbngtk ot dfe sdring varibe.
De imitad strings
Hlee soring is ended ith a dolimter

shring
Nal churactr is t most commony sed saring
Aslimitr in the c larguag
Dperations on strings
- In c eharatlars can be manipuatc in e Bame
wy a we do with numbers.
when We wwe a charaer conatont or aa husatr
tonver ted int
to an inlager valu. hee valie
local haate st ot t syiim
dapedi
HrBo
int i;
char eh 'A':
i= ch;
printt (" . d", i);
I/Prints 6, AScII yalu of ch iss 'A.
iy Finding shring
-The nmber at
ot charactcs in ke string constiutes
the langth of tfe sting
dample:- LEN6iTH("C PRoGRAMMNG 1S FUN")
will return 90. where even blan KSpues are coun tecl
chutd.
write aa prerm to find the kath of stig.
#in luce <stelioh
incluele <con io.h
nt mouin c)

char str [iv0], i0, lenth;


clrser);
prinf("n dnter the striny:");
gets (etr);
Nhile (str[i34E\o)

lenq th ij
printt ("\ Tk Loqth of die cring it:
length)
>rite proom to tenvet cha vacte r ot a gdaintt
to

t incuce <s+dio. h>


+indte ceni0. h
tnt main )
thar r[ieo] upper tasestrliooJ,

printf("ln inte the shrin

Case i )
in to Lpper ose.
(oner ting characers of o strine
-Inc he AscTI coces are sdovccl inseacl of the
Yecl value.
haracter to
So t we have to con vert aa lower cae
pper cose, hen we jst ned do substrat 2 from
the AS cII vaue ot h characster.

(onverting characters of a sting into Lowey case.


|o convert an úpper teue charater into Lower ceu
its AscII vlue.
thn Ne just ned to acld 32 to
a prvgran to convert characters of a atrinq ito
Lower couse.
t incluce <stlio.h
incuele <conio. hy
int maun ()

char str (1oD]. lowe r str (iol;


int i =o, j= 0)

print f ("\ner the striny


qets (at r);
while (str[i]!\o')
it (ctr[i]>=A 4-a st ri3<'z)
Lower s4r[;3 = str[i3+3
else
lower strli3gtr[i3;
lower s t r l i \
The string converted into ower case is ");
primi ("n
puts(lo werstr);
Yeturn 0

Con tatenating two strings do crm e Nen ctoing


L S1 and S2 are 2 strings kn cencatnation
Operatiorn proclues a string hh contuns charattirs
ot s1 to llowed by the eharactas df s2
wride a proyram to conca tenat two stringe.
t* inlude <stdio,h
#* inducle <conio.h>
int man )
lchar str1[ro], str2[io], strs[in3;
int i=0, j=0;
clrserc);
print4C"ln Enter th frst strin ");
etsstr 1);
printf("ln fntr the Seuond string");
gets (stra);
ohile (stri] le\o')
str 3Ci]= Str 1iJ;
Itt)
i=0;
while Gt re [iJI= ho')

Str3[i]strCiJ;

str3[J =\o';
printf(The oncatenate string is:)
puts (str3);
qetch ();
Yeturn o,

Agpendeng string to Another string.


Appending one strinq to another etriny involves topying
string at he end of the
-

Hhe tontents of the source


des tination string
- txe- t S1 eandl s2 ere 2 <triny S Rencontappending
tint
we hewe to adlel e
S1 to S2 meng

write a program to ppenc e string to onokr strig


t induce <s+dio.h
ir inlude <conio.h>
iot mnuin ()
s-tr(so3;
char Deg t. str[ioo], ouree
Printf ("ln nter he soure string:")
oets (sourcestr);
print.f(n Eoter Jhe cles tinaton ctring ");
jets (Dest str;
while (Dest StrliJ! o ' )
it+;
nhile Co urce st r[]! '\o')
Dest str[iJ= SourestrsJs

Dest stri]'\o';
printt ("\n After appenclinq, the destinatin
string is:";
puts(Dest str);
qetch ();
Yeturn 0;
.
CHr36)

lompariny Awo strins


14 S1 and S are
- stritjs then conpainq 2.
Srings roill eqive either of se results.
and s 2 qre cqal
b>S1 >s2, hen in oietionary orcer S1 ni!
Come etter s2. orcler s1 preceele s
C)s1 << s2, hen in olu tionary
S2,

To (ompnre eah dand every ctar aler


shing'
both }he sErings.
1s tomparel fom
-I44 all Hhe choructs are same hen k 2 strings
oSu said do be cqual.
>wrde a proqram to compare 2 sthings
inluee <stdio.hs
incluce <conid. h
inecde <stringh
int meun ()

har str [so], stre[so3;

crserc);

qets(str,
printf ("ln tnter the number ot charactors du
be copid: ");
eanf("-d, n);
i0;
ohile (striJe l = o ' -d í<n)
Substr :]= str[iJ:

printf ("\h The stlbstrng is: ");


Puts (substr);
getch();
return 0;

In ser tinq e strinq in Another string.


cperation insers a strínq s in
- The in Serdion ope he
p0s ithon.
main tet T at Kth position.
gentral syntox ot Ris operation is:
-The
TNSERT (te xt; postion, strin)
Write a proram to in serta strinq in the main kd
# inlucle < stelio. h>
ineluele <on io.hs
int main ()

char tet [iD], str[e0], ins_te+ Liool;


int izo, (=0, K=D, pos
clrscr l);
pirtt (" oter the min text ");
gts Cteat); rtecl)
strinr be tn se
pritt( n nter he
gets (str): the tring
printf("n Enter Hhe position et hich
has to be insertel ");
Sant (".d", 4 p0s );
whil (text fi] l='\o')
it (=pos)
ohil str [u] =' \o)
ins_ text []: str Cn];

4
ins text CiJ text [iJ;
J+t;

îns-text J='\o':
printt(\n The ne string
puts(ins-tet);
qetch);
> write a proqraro to deleli a substring doma tot,
GakajyothiStassSe SindtEFuBAettkastaka.cavaig)
=inlude <stlío.h>
-t* inclutelo <conio. h>
int maun()
char tex +[200], str [2o], newtex+[200J;
int izo, iz 0, K, n=9 topy_loop =0;
clrscro;
print ( In nter the maun text ");
ets (text);
printf("n Enter the strin do be dloltd ");
qets (str);
while (te xt SrJ ! :'ho')
4
f ] = str[sJ4- str[i!=\o')
ohile (tet

Copy loop K;
tezt [opy loopJ
new teztLn]
itt
Copy- oop tt;
ntt)
c40 )
newctrfnJlo
printf (" n the new strinq is "):
puts (new_dext);
qetch l);
eturn 0;

Mscelantos strine and haracteY furtns.


character Menipulaton funution
Funtoo
>ísalnumn (inte) chechs hether charactr e is
alphanmeric eharactor

>isalph (int ) chechs whether eharater e an


alphabetie charactl.
is cntl (inte) chechs hther characterc is a
Control charater.
isdiyt(int c) checks whetkr charater cc isa cieqid
isqraphl) hecks whe ther ehaac ve is ae qrephie
or pinlng cheratr. The fanction lda
Re whi t space cha'sact.
ispintinte) chetks ohether character e s a piating
chezactr.The finetion inelucles dê di
Spae cha'rater.
>islewer(iole) cheelhs whether Hhe chaucler c
in loweY case.
>is wpper(intc) checdhs nhether the charater e is
in pper caye.
>ispunt Cintc) chechs whether he characttre is
punctuation marh,
is space (inte) cheche whether he character e is
a nhite spau charattir.
>isx dipt(nt e) chechs whherthe eharater c is
a hexacumal diyt.
>to lower Gint e) Con vert the character e to lower
Case.
Con vevts the charater c to upper
>to ugper (int) Ce

Shring Manipulaton Functons,


atreat nthon,
Synto- char *streat (char tstr1, const char *str),
The strcat fun tron eppencls -the string poined
to by str2 to tfe enel othe string pontd do by
tri.
atrnct funtion
charstro cot lhar *str1, const har r
Syn d -
Sizet n);
-This tnton aqpends t string paintad to by shre
str ehr funton
Syn tox: char *etrehr (ions+ char stY, intc),
The strehrt) fun tion earches gor the fors t
urene o.f the charactir ce (an unsirecd ehar)
in te string pointd do by the arqu ment ctr.
strrchY tuntion
Syntoz chartrrchrlonst char str, int c);
- The strrchr ) huntion sarchey frke first
oUurene of the charatr e Can unsic(ned ehar)
bepinning at tf rar enel endl wor king dtouare
he ont in tke tring pointed to by he argurent
str.
otrcmp funtron tonst char
(const char str ,
Syoo:int stremp *gtr2);

The stremp funtion tompareg Re string pointd to


stri to dfe string pointed to by stre.
by

(tonst char tstr1, tonst ehar


Synta: int strnnp Size_t n):
* re,
The tnchion compares at most -he fist n bydes
cf sr1 and str2. he po ceus BtopS comparing
thehu nul chasacte enounlercd
at der
CArpy fnchion.
8syndd: chor 4repy(chaY st r , tonst char to l
funttion copies Hhe string pointd to by str2 tn
- This haractr of st2. 4 veturns
trl ine haeling he nul
+he aryument trt
strncpy efnction. const char
Syntoz: char* strncpy (ehar str t,
*str2, Size_t n);
This funtion topis up to n charaters trom JAe
Sing poinled do by str2 to stri. Copying sdops
nhen n characts arc copid.

EWe ihnow that a strinq s an erray o


For exam ple,if Ne suy char namefJ-"Mohan')
cheas, scharaitr
string (eharatr qrray) Rat hae
fen name is a
1.f 20stucen o e tkee rin a
loy en we need a
t enll Atucanti, Here
tring ket store names neeoled.
or an array of s tringz it
sriney o strings woulel gtre 20 indivilual
Suh an aray of strings can be deelarecl as
cdrings. An onoy ot ings
char names
where cach
Hlere we alocal Spale 20 names

can be a mainum of 30 characers


name
pregram
Aouclont ota cus.
cles
nams
ioucle <stel:o. h
indu cle <ronioh>

char namuy (5] (io];


i t i, nj

Printf ("lo fader Jhe numbe r of stuclets );


Scant (" %d', -n);
for (i=o; i<n; i++)
printt( \o tnter the naqvmt of stuelernt 1li4):
qet s(ncmey Di]);

fr iz0; i<n; it+)


puts(nqmis [i]);
getch ();

You might also like