Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C ตรวจสอบสตริงสองตัวว่าเหมือนกันหรือไม่ (strcmp)

ได้รับสตริงสองตัว str1 และ str2 ตรวจสอบว่าเหมือนกันทุกตัวอักษรหรือไม่

Identical = ดูเหมือนกันแต่ไม่เหมือน (case-sensitive) เช่น "Hello" vs "hello"
Same = เหมือนกันทุกอย่าง รวมถึง case เช่น "World" vs "World"

ตัวอย่าง

Input: str1="Hello", str2="Hello"  Output: Yes 2 strings are same
Input: str1="world", str2="World"  Output: No, 2 strings are not same

แนวทาง

  • ใช้ strcmp() จาก <string.h>
  • คืนค่า 0 ถ้าเหมือนกันทุกตัว (case-sensitive)
  • คืนค่าไม่ใช่ 0 ถ้าไม่เหมือน

อัลกอริทึม

Start
main():
    กำหนด string1[], string2[]
    if strcmp(string1, string2) == 0
        print "Yes 2 strings are same"
    else
        print "No, 2 strings are not same"
Stop

โค้ดตัวอย่าง

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

int main() {
    char string1[] = "tutorials point";
    char string2[] = "tutorials point";
    if (strcmp(string1, string2) == 0)
        printf("Yes 2 strings are same\n");
    else
        printf("No, 2 strings are not same\n");
    return 0;
}

ผลลัพธ์

Yes 2 strings are same