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

การตัดต่อสตริงใน C# เพื่อหมุนตัวอักษร (String Rotation)

การหมุนสตริง (String Rotation) คือการย้ายตัวอักษรจากด้านหนึ่งไปอีกด้านหนึ่ง โดยใน C# สามารถทำได้ง่ายด้วยเมธอด Substring() ร่วมกับการต่อสตริง

หลักการ

เพื่อหมุนตัวอักษร n ตัวแรกไปไว้ท้ายสตริง:

string rotated = str.Substring(n) + str.Substring(0, n);

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

using System;

public class Program
{
    public static void Main()
    {
        string str = "welcome";
        int rotateCount = 2;

        Console.WriteLine($"Original String = {str}");

        // หมุน 2 ตัวแรกไปท้าย: "we" + "lcome" → "lcomewe"
        string rotated = str.Substring(rotateCount) + str.Substring(0, rotateCount);

        Console.WriteLine($"Rotating {rotateCount} characters: {rotated}");
    }
}

ผลลัพธ์

Original String = welcome
Rotating 2 characters: lcomewe

การประยุกต์ใช้: ฟังก์ชันหมุนสตริงสากล

public static string RotateString(string input, int positions)
{
    if (string.IsNullOrEmpty(input) || positions == 0)
        return input;

    // จัดการค่าที่เกินความยาวและค่าลบ
    positions = positions % input.Length;
    if (positions < 0)
        positions += input.Length;

    return input.Substring(positions) + input.Substring(0, positions);
}

กรณีการใช้งานจริง

  • อัลกอริทึมเข้ารหัสง่ายๆ (Caesar Cipher แบบหมุนตัวอักษร)
  • การสลับตำแหน่งข้อมูลใน buffer แบบ Circular Buffer
  • เกมปริศนาคำ (Word Puzzle Games)
  • การทดสอบอัลกอริทึม String Matching

หมายเหตุประสิทธิภาพ

สำหรับการหมุนหลายครั้งหรือสตริงยาวมาก ควรพิจารณาใช้ StringBuilder หรืออัลกอริทึม In-place Rotation เพื่อลดการจัดสรรหน่วยความจำ