หน้าหลัก » ภาษาซี (C) » โค้ดภาษาซี วิธีต่อข้อความ (String)

โค้ดภาษาซี วิธีต่อข้อความ (String)




ตัวอย่างโค้ดภาษาซี สำหรับการต่อ string หรือต่อคำ โดยการใช้ strcat สามารถทำได้ดังนี้

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

/***************************************************
 * Author    : CS Developers
 * Author URI: https://www.comscidev.com
 * Facebook  : https://www.facebook.com/CSDevelopers
 ***************************************************/
 
#include <stdio.h>
#include <string.h>

int main()
{
	char str[100] = " CS ";
	
	strcat(str, "Developers ");
	strcat(str, "URL: ");
	strcat(str, "https://www.comscidev.com/ ");
	
	printf("\n%s\n", str);
	
	return 0;
}

อธิบายเพิ่มเติม

  • จะต้อง include <string.h> ถึงจะใช้งาน strcat ได้
  • การใช้งาน strcat จะต้องส่ง parameter 2 ค่าเข้าไป ตัวแรกจะเป็น string หลัก และตัวที่ 2 จะเป็น string ที่ต้องการนำไปต่อท้าย string หลัก
  • strcat(“CS “, “Developers”); เมื่อแสดงผลจะได้ CS Developers

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

/***************************************************
 * Author    : CS Developers
 * Author URI: https://www.comscidev.com
 * Facebook  : https://www.facebook.com/CSDevelopers
 ***************************************************/
 
#include <stdio.h>
#include <string.h>

int main()
{
	char str[100];
	
	strcpy(str, " CS ");
	
	strcat(str, "Developers ");
	strcat(str, "URL: ");
	strcat(str, "https://www.comscidev.com/ ");
	
	printf("\n%s\n", str);
	
	return 0;
}

อธิบายเพิ่มเติมสำหรับโค้ด 2

  • ไม่ได้กำหนดค่าเริ่มต้นให้ string
  • ใช้ strcpy เพื่อกำหนดค่าเริ่มต้นให้กับตัวแปร str
  • ใช้ strcat เพิ่มค่า string เข้าไปต่อท้าย

แสดงผล

โค้ดภาษาซี วิธีต่อข้อความ (String)