C 中自定義字串格式

2021-08-15 03:20:58 字數 1475 閱讀 5106

一、輸出字串的時候可以按照格式輸出,數字的常用格式如下表所示:  

下面給出示例:

int a = 23;

// 使用 string 型別的 format 方法可以按照格式輸出,並制定小數點之後的位數

string result = string.format("",a); // result = "23.000"

string result1 = string.format("",a); // result1 = "2300.0%"

double b = 3.1415;

// # 表示數字站位,數字可用才顯示。0 表示零站位,數字不可用顯示 0

string result2 = string.format("",b); // result = "3.142"

string result3 = string.format("",b); // result = "03.142"

注意:

1、數字的格式字串不區分大小寫;

2、可以使用 string 型別的 format 方法指定輸出字串小數點後的位數。

二、自定義字串格式

使用自定義的字串格式需要實現介面 iformattable 介面,該介面只有乙個 帶兩個引數的tostring()方法,乙個引數是格式,另乙個是 iformatprovids 介面型別的引數。第二個引數可以為空,實際操作不許理會。

下面給出示例:

// 自定義的乙個資料類

public class format:iformattable

// 重寫基類的 tostring 方法,返回姓名

public override string tostring()

// tostring 過載

public string tostring(string format)

// 實現介面的 tostring 方法來自定義格式

public string tostring(string format,iformatprovider formatprovider)}}

下面給出呼叫示例:

format f = new format("老","胡");

string r0 = f.tostring(); // r0 = "老胡"

string r = f.tostring("f"); // r = "老"

// string 型別的format方法會匹配合適的 tostring 方法呼叫

string r1 = string.format("",f); // r1 = "老"

string r2 = string.format("",f); // r1 = "胡"

C 自定義字串類

ifndef header h define header h define defaultsize 128 include include includeusing namespace std class mystring circle while this ch i pat.ch 0 icurl...

00802 自定義字串輸出格式

通過 format 函式和字串方法使得乙個物件能支援自定義的格式化 重新 format 鉤子函式 usr bin env python formats mdy dmy class date def init self,year,month,day self.year year self.month ...

自定義字串排序

字串s和 t 只包含小寫字元。在s中,所有字元只會出現一次。s 已經根據某種規則進行了排序。我們要根據s中的字元順序對t進行排序。更具體地說,如果s中x在y之前出現,那麼返回的字串中x也應出現在y之前。返回任意一種符合條件的字串t。示例 輸入 s cba t abcd 輸出 cbad 解釋 s 現了...