பாடம் 1 / 6 · Strings, Structs, Files · படிக்க 2 min · புதுப்பிக்கப்பட்டது

Strings-ஓட வேலை செய்யுறது

C-ல தனியா string-ன்னு ஒரு type கிடையாது. அதுக்கு பதிலா என்ன இருக்கு, அதை எப்படி safe-ஆ use பண்ணணும்.

C-ல string type கிடையாது. ஒரு string-ன்னா, கடைசில \0 byte-ல முடியும் ஒரு char array தான். C-ல இருக்குற ஒவ்வொரு string function-ம் இந்த \0 terminator இருக்கும் என்று நம்பித்தான் வேலை செய்யும்.

c
#include <stdio.h>
#include <string.h>

int main(void)
{
    char first[20] = "Priya";
    char last[20]  = "Raman";
    char full[50];

    strcpy(full, first);
    strcat(full, " ");
    strcat(full, last);

    printf("%s\n", full);
    printf("%d characters\n", (int) strlen(full));

    if (strcmp(first, last) != 0) {
        printf("The names differ\n");
    }

    return 0;
}
Output
Priya Raman
11 characters
The names differ

நீங்க use பண்ணப் போற functions

  • strlen(s) — string-ல எத்தனை characters இருக்குன்னு சொல்லும். \0 terminator-ஐ count பண்ணாது.
  • strcpy(dest, src) — src-ல இருக்குற string-ஐ dest-க்கு copy பண்ணும்.
  • strcat(dest, src) — dest-ஓட கடைசில src-ஐ சேர்த்து ஒட்டும்.
  • strcmp(a, b) — ரெண்டும் ஒண்ணா இருந்தா 0 return பண்ணும். இது true/false இல்ல; அதனால result-ஐ 0-வோட compare பண்ணுங்க.

Warning

strcpy-ம் strcat-ம் destination-ல போதுமான இடம் இருக்கான்னு check பண்ணாது. எல்லையைத் தாண்டி எழுதினா, அதுக்கு buffer overflow-ன்னு பேரு — பல security vulnerabilities-க்கு இதுதான் காரணமா இருந்திருக்கு. Destination-க்கு தாராளமா இடம் ஒதுக்குங்க; முடிஞ்ச அளவுக்கு snprintf use பண்ணுங்க.

ஒரு வரி text படிக்கிறது

c
char name[50];

printf("Your name: ");
fgets(name, sizeof(name), stdin);

/* fgets keeps the newline; trim it off. */
name[strcspn(name, "\n")] = '\0';

printf("Hello, %s!\n", name);

Note

Text input வாங்க scanf("%s")-க்குப் பதிலா fgets use பண்ணுங்க. scanf("%s") ஒரு space வந்ததும் நின்னுடும்; உங்க buffer எவ்வளவு பெருசுன்னும் அதுக்குத் தெரியாது. fgets-க்கு எவ்வளவு அளவுன்னு சொல்லலாம், அதை மதிச்சுத்தான் input வாங்கும்.

ரெண்டு strings ஒண்ணா இருக்கும்போது strcmp(a, b) என்ன திருப்பி தரும்?

Create a free account to save your progress, or sign in.