簡體   English   中英

如何在字符串C#中的最后3個字符前插入空格?

[英]How to insert space before the last 3 characters in a string C#?

我正在使用Windows窗體,我正在構建用戶進入英國PostCode的應用程序。

UK PostCode在最后3個字符之前包含空格,例如:

L22 9QYL5 3SGWA10 4RT因此在最后3個字符之前總是有空格。 我想要做的是:當用戶像這個L53SG一樣輸入他們的PostCode時,我想在最后3個字符之前插入空格,使其像L5 3SG

說我們有:

string PostCode = "L53SG"; 

如何在PostCode字符串中的最后3個字符前插入空格?

任何人都知道如何做到這一點。 謝謝

您可以使用string.Insertstring.Length輕松完成此操作:

string insertedStr = str.Insert(str.Length - 3, " ");

string.Length將返回string的長度,並將其減去3,您可以獲得要插入space的索引位置。

最后,您只需要使用string.Insert(index, value)來插入替換string (在您的情況下是空格( " " ))

postCode = postCode.Replace(" ", "");
if (postCode.Length > 3)
    postCode = postCode.Insert(postCode.Length - 3, " ");

首先刪除那里的任何空格,然后確保至少有3個字符(我們可能希望在這種情況下拋出異常,因為它不是您使用其余部分的有效輸入)並向后插入3個空格。

可以看到用戶是否輸入了空格並且如果他們這樣做則跳過該過程,但這種方式更簡單並且捕獲用戶在錯誤的位置添加一個空格的情況。

如果需要,可以先刪除字符串中的任何空格:

PostCode = PostCode.Replace(" ", string.Empty);

然后,使用Insert()方法:

string PostCode = "L53SG";
PostCode = PostCode.Insert(PostCode.Length - 3, " ");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM