C#中string用法

C#中string用法
C#中string用法

一、标记

标记(tokenizing)是从文本中提取具体内容的过程。

下面的代码从句子中提取单词,并把它们输出到控制台。

class mytokenizing

{

static void main(string[ ] args)

{

string mystring="i like this food,are you?";

char[] separators={ ,,,?,:,!};

int startpos=0;

int endpos=0;

do

{

endpos=mystring.indexofany(separators,startpos);

if ( endpos==-1 ) endpos=mystring.length;

if ( endpos!=startpos )

console.writeline(mystring.substring( startpos,(endpos-startpos)));

startpos=(endpos+1);

}while(startpos

}

}

i <== 输出

like

this

food

are

you

二、颠倒字符串次序

class myreverse

{

static void main(string [] args)

{

string mystring="你们好";

char[] mychars=mystring.tochararray( );

array.reverse(mychars);

console.writeline(mystring);

console.writeline(mychars);

}

}

任何继承于array的类都能利用reverse( )方法为数组中的元素重新排序。

三、字符串的插入、删除和替换

示例文件test.txt为字符串的来源。下面代码以unicode格式读取文本。确保文件保存为读

取时的格式。例如记事本允许将代码保存为unicode:

aaaaaaaa,bbbbbbbb,cccccc

dddddddd,eeeeeeee,ffffff

gggggggg,hhhhhhhh,iiiiii

jjjjjjjj,kkkkkkkk,llllll

下面代码加载数据并处理数据的测试工具。测试结果发送给控制台。

class myprocessfile

{

static void main(string [] args)

{

const string myname="test.txt";

stream readline;

textwirter writeline;

stringbuilder sb;

readline=file.openread(myname);

writeline=console.out;

streamreader readlinesreader=new streamreader(readline,encoding.unicode); readlinesreader.basestream.seek(0,seekorigin.begin);

while(readlinesreader.peek()>-1)

{

sb=new stringbuilder(readlinesreader.readline());

//插入字符串操作语句如:sb.append(",123");

console.writeline(sb.tostring());

}

}

}

在结尾添加一列内容:

//displays aaaaaaaa,bbbbbbbb,cccccc,xxxxx

//......

sb.append(",xxxxx");

第一列可以使用下面的代码删除:

//displays bbbbbbbb,cccccc

//......

sb.remove(0,sb.tostring().indexof(,)+1);

替换分隔符:

//aaaaaaaa+bbbbbbbb+cccccc

sb.replace(,,+);

添加行号(linenumber已经在前面某处声明过为前提):

sb.insert(0,linenumber.tostring("000 "));

linenumber++;

//displays

//000 aaaaaaaa,bbbbbbbb,cccccc

//001 dddddddd,eeeeeeee,ffffff

//002 gggggggg,hhhhhhhh,iiiiii

//003 jjjjjjjj,kkkkkkkk,llllll

13:16 | 评论(0)

2004年7月11日#

字符串操作学习笔记

字符串操作

--------------------------------------------------------------------------------

1、从字符串中提取子串

stringbuilder 类没有支持子串的方法,因此必须用string类来提取。

string mystring="my name is ynn.";

//displays "name is ynn."

console.writeline(mystring.substring( 3 ));

//displays "ynn"

console.writeline(mystring.substring( 11,3 ));

2、比较字符串

string 类有四种方法:compare( )、compareto( )、compareordinal( )、equals( )。compare( )方法是compareto( )方法的静态版本。只要使用“=”运算符,就会调用equals( )方法,的以equals( )方法与“=”是等价的。compareordinal( )方法对两个字符串比较不考本地语言与文件。

示例:

int result;

bool bresult;

s1="aaaa";

s2="bbbb";

//compare( )method

//result值为“0”表示等,小于零表示s1 < s2,大于零表示s1 > s2

result=https://www.360docs.net/doc/817107364.html,pare(s1,s2);

result=https://www.360docs.net/doc/817107364.html,pareto( s2 );

result=https://www.360docs.net/doc/817107364.html,pareordinal(s1,s2);

bresult=s1.equals( s2 );

bresult=string.equals( s1,s2 );

一个例外情况是,两个字符串都是内置的,并相等,静态方法要快得多。

3、字符串格式化

3.1 格式化数字

格式字符说明和关联属性

--------------------------------------------------------------------------------

c、c 货币格式。

d、d 十进制格式。

e、e 科学计数(指数)格式。

f、f 固定点格式。

g、g 常规格式。

n、n 数字格式。

r、r 往返格式,确保将已转换成字符串的数字转换回数字时具有与原数字相同的值。

x、x 十六进制格式。

--------------------------------------------------------------------------------

double val=math.pi;

console.writeline(val.tostring( )); //displays 3.14159265358979

console.writeline(val.tostring("e"));//displays 3.141593e+000

console.writeline(val.tostring("f3");//displays 3.142

int val=65535;

console.writeline(val.tostring("x")); //displays ffff

console.writeline(val.tostring("x")); //displays ffff

single val=0.123f;

console.writeline(val.tostring("p")); //displays 12.30 %

console.writeline(val.tostring("p1")); //displays 12.3 %

默认格式化会在数字和百分号之间放入一个空格。定制方法如下:

其中numberformatinfo类是system.globalization命名空间的一个成员,因此该命名空间必须导入到程序中。

single val=0.123f;

object myobj=numberformatinfo.currentinfo.clone( ) as numberformatinfo; numberformatinfo myformat=myobj as numberformatinfo;

myformat.percentpositivepattern=1;

console.writeline(val.tostring("p",myformat)); //displays 12.30%;

console.writeline(val.tostring("p1",myformat)); //displays 12.3%;

格式化具有很大的灵活性。下面的例子演示一个没有意义的货币结构:

double val=1234567.89;

int [] groupsize={2,1,3};

object myobj=numberformatinfo.currentinfo.clone( );

numberformatinfo mycurrency=myobj as numberformatinfo;

mycurrency.currencysymbol="#"; //符号

mycurrency.currencydecimalseparator=":"; //小数点

mycurrency.currencygroupseparator="_"; //分隔符

mycurrency.currencygroupsizes=groupsize;

// 输出#1_234_5_67:89

console.writeline(val.tostring("c",mycurrency));

3.2 格式化日期

输出形式取决于用户计算机的文化设置。

using system;

using system.globalization;

public class mainclass

{

public static void main(string[] args)

{

datetime dt = datetime.now;

string[] format = {"d","d","f","f","g","g","m","r","s","t", "t","u", "u","y","dddd, mmmm dd yyyy","ddd, mmm d \"\"yy","dddd, mmmm dd","m/yy","dd-mm-yy",};

string date;

for (int i = 0; i < format.length; i++)

{

date = dt.tostring(format[i], datetimeformatinfo.invariantinfo);

console.writeline(string.concat(format[i], " :" , date));

}

}

}

d :07/11/2004 <=======输出

d :sunday, 11 july 2004

f :sunday, 11 july 2004 10:52

f :sunday, 11 july 2004 10:52:36

g :07/11/2004 10:52

g :07/11/2004 10:52:36

m :july 11

r :sun, 11 jul 2004 10:52:36 gmt

s :2004-07-11t10:52:36

t :10:52

t :10:52:36

u :2004-07-11 10:52:36z

u :sunday, 11 july 2004 02:52:36

y :2004 july

dddd, mmmm dd yyyy :sunday, july 11 2004

ddd, mmm d ""yy :sun, jul 11 04

dddd, mmmm dd :sunday, july 11

m/yy :7/04

dd-mm-yy :11-07-04

3.3 格式化枚举

enum classmen

{

ynn=1,

yly=2,

css=3,

c++=4

}

获取枚举字符串信息如下:

classmen myclassmen=classmen.yly;

console.writeline(myclassmen.tostring( )); //displays yly

console.writeline(myclassmen.tostring("d")); //displays 2

从系统枚举中获取文本人信息如下:

dayofweek day=dayofweek.friday;

//displays "day is friday"

console.writeline(string.format("day is {0:g}",day));

格式化字符串“ g ”把枚举显示为一个字符串。

11:56 | 评论(0)

2004年7月8日#

stringbuilder 类学习笔记

string类的不可改变性使它更像一个值类型而不是一个引用类型。其副作用是每次执行字符操作时,都会创建一个新的string对象。stringbuilder 类解决了对字符串进行重复修改的过程中创建大量对象的问题。

stringbuilder 类的一些属性与方法

--------------------------------------------------------------------------------

length属性并不是只读的。

stringbuilder sb=new stringbuilder("i live the language");

console.writeline(sb.tostring( ));

sb.length = 6;

//displays "i live"

console.writeline(sb.tostring( ));

capacity 属性

描述:当前为实例分配的字符数量。默认容量是16,如果将一个字符串作为参数提供给构造函数,容量以最接近2 的幂的值。

maxcapacity 属性

描述:这个实例中可以被分配的字符最大数量。

append( )方法

描述:追加给定值的字符串表示。

stringbuilder sb=new stringbuilder( );

console.writeline( sb.capacity+"\t"+sb.length );

sb.append ( a , 17 )

console.writeline( sb.capacity+"\t"+sb.length );

16 0 <== 输出

32 17

ensurecapacity( int capacity ) 方法

描述:如果当前容量小于指定容量,内存分配会增加内存空间以达到指定容量。

replace( char oldchar,char newchar ) 方法

描述:用newchar替换oldchar。

replace( string oldstring,string newstring ) 方法

描述:用newstring替换oldstring。

replace( char oldchar,char newchar,int startpos,int count ) 方法

描述:从startpos到count-1之间用newchar替换oldchar。

replace( string oldstring,string newstring,int startpos,int count ) 方法

描述:从startpos到count-1之间用newstring替换oldstring。

tostring( ) 方法

stringbuilder sb=new stringbuilder( "i live this game" );

string s1=sb.tostring( ); //displays "i live this game"

string s2=sb.tostring(3,4); //displays "live"

在这里第二个tostring( )方法调用了string类的substring( )方法

public string tostring( int startindex,int length )

{

return m_stringvalue.substring( startindex,length );

}

10:28 | 评论(0)

2004年7月7日#

string 类学习笔记

一、string 类的常用公共成员

--------------------------------------------------------------------------------

compare(string s1,string s2) 静态方法

功能:区分大小写比较。

compare(string s1,string s2,bool ignorecase) 静态方法

功能:ignorecase为true,不区分大小写比较。

compareto(string s) 实例方法

功能:对给定字符串与实例字符串执行一次区分大小写与文化信息比较。

copy(string s) 静态方法

功能:返回一个与给定字符串同值的新的字符串。

copyto(int surceindex,char[ ] destination,int destindex,int count)

实例方法功能:此实例中的指定位置复制到unicode 字符数组中的指定位置。参数:

sourceindex:此实例中的字符位置。

destination :unicode 字符的数组。

destindex :destination 中的数组元素。

count:此实例中要复制到destination 的字符数。

例程:

using system;

public class copytotest {

public static void main() {

string strsource = "changed";

char [] destination = { t, h, e, , i, n, i, t, i, a, l, , a, r, r, a, y };

console.writeline( destination );

strsource.copyto ( 0, destination, 4, strsource.length );

console.writeline( destination );

strsource = "a different string";

strsource.copyto ( 2, destination, 3, 9 );

console.writeline( destination ); }

}

输出:

the initial array

the changed array

thedifferentarray

endswith(string s)

功能:如果实例字符串是以给定的字符串结束,就返回true。

equals(string s)

功能:如果实例字符串与给定的对象具有相同的值,就返回true。

format(iformatprovider provider,string format,paramarray args)

功能:format 的一个副本,其中格式项已替换为args 中相应object 实例的string 等效项。

参数

provider : 一个iformatprovider,它提供区域性特定的格式设置信息。

format : 包含零个或多个格式项。

args :包含零个或多个要格式化的对象的object 数组。

例如:

string myname = "fred";

string.format("name = {0}, hours = {1:hh}", myname, datetime.now);

固定文本是“name =”和“, hours =”,格式项是“{0}”和“{1:hh}”,值为myname 和datetime.now。

replace(string oldstring,string newstring)

功能:在实例字符串中用newstring替换所有oldstring。

split(char[] separator,int count)

参数

separator :分隔此实例中子字符串的unicode 字符数组、不包含分隔符的空数组或空引用。

count :要返回的最大数组元素数。

例如:

string delimstr = " ,.:";

char [] delimiter = delimstr.tochararray();

string words = "one two,three:four.";

string [] split = null;

split = words.split(delimiter, 4);

foreach (string s in split)

{

console.writeline("-{0}-", s);

}

one <==输出

two

three

four.

substring(int startpos,int length)

功能:从指定位置开始返回一个指定长度的子串。

tostring( ) 功能:返回一个对实例字符的引用。

tostring(iformatprovider format)

功能:返回一个对实例字符串的引用。

13:31 | 评论(0)

2004年7月6日#

正则表达式学习笔记(1)

一、system.text.regularexpression命名空间

1、regex类可以用来创建正则表达式,还提供了许多方法。

如:regex.replace(string input,string pattern,string replacement);

-------regexoption枚举

ignorecase 忽略大小写。默认情况区分大小写

righttoleft 从右到左查找输入字符串。

none 不设定标志。

miltiline 指定^与$可以匹配行的开头和结尾,以及字符串的开头和结尾。

singleline 规定特殊字符“.”匹配任一字符。换行符除外。

例:regexoptions.ignorecase

regex.ismatch(mystring,"ywsm",regexoptions.ignorecase |regexoptions.righttoleft):

-------(两个主要的)类构造函数

regex(string pattern);

regex(string pattern , regexoption options);

例:匹配ywsm:

static void main(string[] args)

{ regex myregex=new regex("ywsm");

system.console.writeline(myregex.ismatch("the first three letters of "+"the alphabet are ywsm")); }

输出:true如需设置区分大小写可用

regex myregex=new regex("ywsm",regexoption.ignorecase);

-------ismatch( )方法

该方法可以测试字符串,看它是否匹配正则表达式的模式。如果发现了一次匹配,返回true,否则为false。ismatch( )有一个静态的重载方法,使用它时可以无需显式创建一个regex对象。

重载形式:

public bool regex.ismatch(string input );

public bool regex.ismatch(string input,int startat);

public static bool regex.ismatch(string input,string pattern);

public static bool regex.ismatch(string input,string pattern,regexoption options);

input: 指定了包含将检索的文本的字符串。

sartat: 指定了搜索的起始字符位置。

pttern: 指定将匹配的样式。

options: 匹配行为的选项。

例:string inputstring="welcome to the ywicc,ywsmxy!";

if ( regex.ismatch( inputstring,"ywicc",regexoptions.ignorecase) )

console.writeline("match found");

else

console.writeline(" no match found");

------replace( )方法

用指定的字符串代替一个匹配模式。

---基本方法有:

public static string regex.replace(string input,string pattern,string replacement);

public static string regex.replace(string input,string pattern,string replacement,regexoption options);

例:用"aaa"替换"bbb"的所有实例代码:

string inputstring="welcome to the aaa!";

inputstring=regex.replace(inputstring,"bbb","aaa");

console.writeline(inputstring);

----非静态方法,可以指定替换次数的最大值以及开始下标:

public string replace(string input,string replacement);

public string replace(string input,string replacement,int count);

public string replace(string input,string replacement,int count,int startat);

例:使用xxx替换456之后的123,最多替换两次,代码如下:

string inputstring="123,456,123,123,123,789,333";

regex regexp=new regex("123");

inputstring=regexp.replace(inputstring,"xxx",2,4)

console.writeline(inputstring);

输出:123,456,xxx,xxx,123,789,333

-------split( )方法

在每次发现匹配的位置拆分字符串。返回一个字符串数组。

using system;

using system.text;

using system.text.regularexpressions;

using system.windows.forms;

class mysplit

{

static void main(string[ ] args)

{

string inputstring="123,456,789,ads";

string[ ] splitresults;

splitresults=regex.split(inputstring,",");

stringbuilder resultsstring=new stringbuilder(32);

foreach(string stringelement in splitresults)

{

resultsstring.append(stringelement+"\n");

}

messagebox.show(resultsstring.tostring( ));

}

}

123 <==结果456

789

ads

STRING类函数用法总结3

C++中的string类 前言:string的角色 1string使用 1.1充分使用string操作符 1.2眼花缭乱的string find函数 1.3string insert,replace,erase2string和C风格字符串 3string和Charactor Traits 4string建议 5小结 6附录前言:string的角色 C++语言是个十分优秀的语言,但优秀并不表示完美。还是有许多人不愿意使用C或者C++,为什么?原因众多,其中之一就是C/C++的文本处理功能太麻烦,用起来很不方便。以前没有接触过其他语言时,每当别人这么说,我总是不屑一顾,认为他们根本就没有领会C++的精华,或者不太懂C++,现在我接触perl,php,和Shell脚本以后,开始理解了以前为什么有人说C++文本处理不方便了。 举例来说,如果文本格式是:用户名电话号码,文件名name.txt Tom23245332 Jenny22231231 Heny22183942 Tom23245332 ... 现在我们需要对用户名排序,且只输出不同的姓名。 那么在shell编程中,可以这样用: awk'{print$1}'name.txt|sort|uniq 简单吧? 如果使用C/C++就麻烦了,他需要做以下工作: 先打开文件,检测文件是否打开,如果失败,则退出。 声明一个足够大得二维字符数组或者一个字符指针数组 读入一行到字符空间 然后分析一行的结构,找到空格,存入字符数组中。 关闭文件 写一个排序函数,或者使用写一个比较函数,使用qsort排序 遍历数组,比较是否有相同的,如果有,则要删除,copy... 输出信息 你可以用C++或者C语言去实现这个流程。如果一个人的主要工作就是处理这种

string类的使用教程

这个是string类的使用教程,可以参考一下 之所以抛弃char*的字符串而选用C++标准程序库中的string类,是因为他和前者比较起来,不必担心内存是否足够、字符串长度等等,而且作为一个类出现,他集成的操作函数足以完成我们大多数情况下(甚至是100%)的需要。我们可以用= 进行赋值操作,== 进行比较,+ 做串联(是不是很简单?)。我们尽可以把它看成是C++的基本数据类型。 好了,进入正题……… 首先,为了在我们的程序中使用string类型,我们必须包含头文件。如下:#include //注意这里不是string.h string.h是C字符串头文件 1.声明一个C++字符串 声明一个字符串变量很简单: string Str; 这样我们就声明了一个字符串变量,但既然是一个类,就有构造函数和析构函数。上面的声明没有传入参数,所以就直接使用了string的默认的构造函数,这个函数所作的就是把Str初始化为一个空字符串。String类的构造函数和析构函数如下: a) string s; //生成一个空字符串s b) string s(str) //拷贝构造函数生成str的复制品 c) string s(str,stridx) //将字符串str内“始于位置stridx”的部分当作字符串的初值 d) string s(str,stridx,strlen) //将字符串str内“始于stridx且长度顶多strlen”的部分作为字符串的初值 e) string s(cstr) //将C字符串作为s的初值 f) string s(chars,chars_len) //将C字符串前chars_len个字符作为字符串s 的初值。 g) string s(num,c) //生成一个字符串,包含num个c字符 h) string s(beg,end) //以区间beg;end(不包含end)内的字符作为字符串s的初值 i) s.~string() //销毁所有字符,释放内存 都很简单,我就不解释了。 2.字符串操作函数 这里是C++字符串的重点,我先把各种操作函数罗列出来,不喜欢把所有函数都看完的人可以在这里找自己喜欢的函数,再到后面看他的详细解释。 a) =,assign() //赋以新值 b) swap() //交换两个字符串的内容 c) +=,append(),push_back() //在尾部添加字符 d) insert() //插入字符 e) erase() //删除字符 f) clear() //删除全部字符 g) replace() //替换字符 h) + //串联字符串 i) ==,!=,<,<=,>,>=,compare() //比较字符串 j) size(),length() //返回字符数量

C++string类型总结

对C++中string类型的总结 string类对象的构造 简化构造函数原型如下(注意,为了简便,把模板中最后一个默认参数省略了): 1: explicit basic_string(); 2: string(const char *s); 3: string(const char *s, size_type n); 4: string(const string& str); 5: string(const string& str, size_type pos, size_type n); 6: string(size_type n, E c); 7: string(const_iterator first, const_iterator last); string对象的操作 字符串比较 支持六种关系运算符(==、!=、>、>=、<、<=),其采用字典排序策略(与C中字符串比较策略完全一样)。这六个关系运算符是非成员的重载运算符。而这些 运算符都支持三种操作数组合:string op string、string op const char*、cons t char* op string(其中op是前面六种关系运算符中任意一种)。解释:提供运算 符的三种重载版本主要是从效率角度考虑的,其避免了临时string对象的产生。 另外,string类还提供了各种重载版本的成员函数compare来比较,简化函数原型为: 1: int compare(const string& str) const; 2: int compare(size_type p0, size_type n0, const string& str); 3: int compare(size_type p0, size_type n0, const string& str, si ze_type pos, size_type n); 4: int compare(const char* s) const; 5: int compare(size_type p0, size_type n0, const char* s) const; 6: int compare(size_type p0, size_type n0, const char* s, size_t ype n) const; 返回值:如果调用该函数的对象的比较序列小于操作数比较序列,则返回负数; 若相等,则返回0;否则,返回正数。

C#中string用法

C#中String用法 标记 标记(tokenizing)是从文本中提取具体内容的过程。 下面的代码从句子中提取单词,并把它们输出到控制台。 class mytokenizing { static void main(string[ ] args) { string mystring="i like this food,are you?"; char[] separators={ ,,,?,:,!}; int startpos=0; int endpos=0; do { endpos=mystring.indexofany(separators,startpos); if ( endpos==-1 ) endpos=mystring.length; if ( endpos!=startpos ) console.writeline(mystring.substring( startpos,(endpos-startpos))); startpos=(endpos+1); }while(startpos

array.reverse(mychars); console.writeline(mystring); console.writeline(mychars); } } 任何继承于array的类都能利用reverse( )方法为数组中的元素重新排序。 字符串的插入、删除和替换 示例文件test.txt为字符串的来源。 下面代码以unicode格式读取文本。确保文件保存为读取时的格式。例如记事本允许将代码保存为unicode: aaaaaaaa,bbbbbbbb,cccccc dddddddd,eeeeeeee,ffffff gggggggg,hhhhhhhh,iiiiii jjjjjjjj,kkkkkkkk,llllll 下面代码加载数据并处理数据的测试工具。测试结果发送给控制台。 class myprocessfile { static void main(string [] args) { const string myname="test.txt"; stream readline; textwirter writeline; stringbuilder sb; readline=file.openread(myname); writeline=console.out; streamreader readlinesreader=new streamreader(readline,encoding.unicode); readlinesreader.basestream.seek(0,seekorigin.begin); while(readlinesreader.peek()>-1) { sb=new stringbuilder(readlinesreader.readline()); //插入字符串操作语句如:sb.append(",123"); console.writeline(sb.tostring()); } } } 在结尾添加一列内容: //displays aaaaaaaa,bbbbbbbb,cccccc,xxxxx //...... sb.append(",xxxxx");

CPPstring类常用函数

C++string类常用函数 string类的构造函数: string(const char *s); //用c字符串s初始化 string(int n,char c); //用n个字符c初始化 此外,string类还支持默认构造函数和复制构造函数,如string s1;string s2="hello";都是正确的写法。当构造的string太长而无法表达时会抛出length_error异常 string类的字符操作: const char &operator[](int n)const; const char &at(int n)const; char &operator[](int n); char &at(int n); operator[]和at()均返回当前字符串中第n个字符的位置,但at函数提供范围检查,当越界时会抛出out_of_range异常,下标运算符[]不提供检查访问。 const char *data()const;//返回一个非null终止的c字符数组 const char *c_str()const;//返回一个以null终止的c字符串 int copy(char *s, int n, int pos = 0) const;//把当前串中以pos开始的n个字符拷贝到以s为起始位置的字符数组中,返回实际拷贝的数目 string的特性描述: int capacity()const; //返回当前容量(即string中不必增加内存即可存放的元素个数) int max_size()const; //返回string对象中可存放的最大字符串的长度 int size()const; //返回当前字符串的大小 int length()const; //返回当前字符串的长度 bool empty()const; //当前字符串是否为空 void resize(int len,char c);//把字符串当前大小置为len,并用字符c填充不足的部分 string类的输入输出操作: string类重载运算符operator>>用于输入,同样重载运算符operator<<用于输出操作。 函数getline(istream &in,string &s);用于从输入流in中读取字符串到s中,以换行符'\n'分开。 string的赋值: string &operator=(const string &s);//把字符串s赋给当前字符串 string &assign(const char *s);//用c类型字符串s赋值 string &assign(const char *s,int n);//用c字符串s开始的n个字符赋值 string &assign(const string &s);//把字符串s赋给当前字符串 string &assign(int n,char c);//用n个字符c赋值给当前字符串 string &assign(const string &s,int start,int n);//把字符串s中从start开始的n个字符赋给当前字符串 string &assign(const_iterator first,const_itertor last);//把first和last迭代器之间的部

string类中函数介绍

标准c++中string类函数介绍 注意不是CString 之所以抛弃char*的字符串而选用C++标准程序库中的string类,是因为他和前者比较起来,不必担心内存是否足够、字符串长度等等,而且作为一个类出现,他集成的操作函数足以完成我们大多数情况下(甚至是100%)的需要。我们可以用= 进行赋值操作,== 进行比较,+ 做串联(是不是很简单?)。我们尽可以把它看成是C++的基本数据类型。 好了,进入正题……… 首先,为了在我们的程序中使用string类型,我们必须包含头文件。 如下: #include //注意这里不是string.h string.h是C字符串头文件 #include using namespace std; 1.声明一个C++字符串 声明一个字符串变量很简单: string Str; 这样我们就声明了一个字符串变量,但既然是一个类,就有构造函数和析构函数。上面的声明没有传入参数,所以就直接使用了string的默认的构造函数,这个函数所作的就是把Str 初始化为一个空字符串。String类的构造函数和析构函数如下: a) string s; //生成一个空字符串s b) string s(str) //拷贝构造函数生成str的复制品 c) string s(str,stridx) //将字符串str内“始于位置stridx”的部分当作字符串的初值 d) string s(str,stridx,strlen) //将字符串str内“始于stridx且长度顶多strlen”的部分作为字符串的初值 e) string s(cstr) //将C字符串作为s的初值 f) string s(chars,chars_len) //将C字符串前chars_len个字符作为字符串s的初值。 g) string s(num,c) //生成一个字符串,包含num个c字符 h) string s(beg,end) //以区间beg;end(不包含end)内的字符作为字符串s的初值 i) s.~string() //销毁所有字符,释放内存 都很简单,我就不解释了。 2.字符串操作函数 这里是C++字符串的重点,我先把各种操作函数罗列出来,不喜欢把所有函数都看完的人可以在这里找自己喜欢的函数,再到后面看他的详细解释。 a) =,assign() //赋以新值 b) swap() //交换两个字符串的内容 c) +=,append(),push_back() //在尾部添加字符

C 中的string常用函数用法总结.

C++中的string常用函数用法总结首先,为了在我们的程序中使用string类型,我们必须包含头文件。 如下: #include //注意这里不是string.h string.h是C字符串头文件 #include using namespace std; 1.声明一个C++字符串 声明一个字符串变量很简单: string Str; 这样我们就声明了一个字符串变量,但既然是一个类,就有构造函数和析构函数。上面的声明没有传入参数,所以就直接使用了string的默认的构造函数,这个函数所作的就是把Str 初始化为一个空字符串。String类的构造函数和析构函数如下: a) string s; //生成一个空字符串s b) string s(str) //拷贝构造函数生成str的复制品 c) string s(str,stridx) //将字符串str内“始于位置stridx”的部分当作字符串的初值 d) string s(str,stridx,strlen) //将字符串str内“始于stridx且长度顶多st rlen”的部分作为字符串的初值 e) string s(cstr) //将C字符串作为s的初值 f) string s(chars,chars_len) //将C字符串前chars_len个字符作为字符串s的初值。 g) string s(num,c) //生成一个字符串,包含num个c字符 h) string s(beg,end) //以区间beg;end(不包含end)内的字符作为字符串s的初值 i) s.~string() //销毁所有字符,释放内存 都很简单,我就不解释了。

C++string类标准库常用函数

C++ string类标准库常用函数 [string类的构造函数] string(const char *s); //用c字符串s初始化 string(int n,char c); //用n个字符c初始化 [string类的字符操作] const char &operator[](int n) const; const char &at(int n) const; char &operator[](int n); char &at(int n); operator[]和at()均返回当前字符串中第n个字符的位置,但at函数提供范围检查,当越界时会抛出out_of_range 异常,下标运算符[]不提供检查访问。 const char *data() const; //返回一个非null终止的c字符数组 const char *c_str() const; //返回一个以null终止的c字符串 int copy(char *s, int n, int pos = 0) const;//把当前串中以pos开始的n个字符拷贝到以s为起始位置的字符数组中,返回实际拷贝的数目 [string的特性描述] int capacity() const; //返回当前容量(即string中不必增加内存即可存放的元素个数) int max_size() const; //返回string对象中可存放的最大字符串的长度 int size() const; //返回当前字符串的大小 int length() const; //返回当前字符串的长度 bool empty() const; //当前字符串是否为空 void resize(int len,char c); //把字符串当前大小置为len,并用字符c填充不足的部分 [string类的输入输出操作] string类重载运算符operator>>用于输入,同样重载运算符operator<<用于输出操作。 函数getline(istream &in,string &s);用于从输入流in中读取字符串到s中,以换行符'\n'分开。 [string的赋值] string &operator=(const string &s); //把字符串s赋给当前字符串 string &assign(const char *s); //用c类型字符串s赋值 string &assign(const char *s,int n); //用c字符串s开始的n个字符赋值 string &assign(const string &s); //把字符串s赋给当前字符串 string &assign(int n,char c); //用n个字符c赋值给当前字符串 string &assign(const string &s,int start,int n);//把s中从start开始的n个字符赋给当前字符串string &assign(const_iterator first,const_iterator last);//把迭代器first和last之间的部分赋给字符串 [string的连接] string &operator+=(const string &s); //把字符串s连接到当前字符串的结尾 string &append(const char *s); //把c类型字符串s连接到当前字符串结尾 string &append(const char *s,int n); //把c类型字符串s的前n个字符连接到当前字符串结尾 string &append(const string &s); //同operator+=() string &append(const string &s,int pos,int n); //把字符串s中从pos开始的n个字符连接到当前字符串的结尾 string &append(int n,char c); //在当前字符串结尾添加n个字符c string &append(const_iterator first,const_iterator last); //把迭代器first和last之间的部分连接到当前字符串的结尾

java 字符串常用函数及其用法

java中的字符串也是一连串的字符。但是与许多其他的计算机语言将字符串作为字符数组处理不同,Java将字符串作为String类型对象来处理。将字符串作为内置的对象处理允许Java提供十分丰富的功能特性以方便处理字符串。下面是一些使用频率比较高的函数及其相关说明。 String相关函数 1)substring() 它有两种形式,第一种是:String substring(int startIndex) 第二种是:String substring(int startIndex,int endIndex) 2)concat() 连接两个字符串 例:String s="Welcome to "; String t=s.concat("AnHui"); 3)replace() 替换 它有两种形式,第一种形式用一个字符在调用字符串中所有出现某个字符的地方进行替换,形式如下: String replace(char original,char replacement) 例如:String s=”Hello”.replace(’l',’w'); 第二种形式是用一个字符序列替换另一个字符序列,形式如下: String replace(CharSequence original,CharSequence replacement) 4)trim() 去掉起始和结尾的空格 5)valueOf() 转换为字符串 6)toLowerCase() 转换为小写 7)toUpperCase() 转换为大写 8)length() 取得字符串的长度 例:char chars[]={’a',’b’.’c'}; String s=new String(chars); int len=s.length(); 9)charAt() 截取一个字符 例:char ch; ch=”abc”.charAt(1); 返回值为’b’ 10)getChars() 截取多个字符 void getChars(int sourceStart,int sourceEnd,char target[],int targetStart) sourceStart 指定了子串开始字符的下标 sourceEnd 指定了子串结束后的下一个字符的下标。因此,子串包含从sourceStart到sourceEnd-1的字符。

c++中string的用法

之所以抛弃char*的字符串而选用C++标准程序库中的string类,是因为他和前者比较起来,不必 担心内存是否足够、字符串长度等等,而且作为一个类出现,他集成的操作函数足以完成我们大多数情况下(甚至是100%)的需要。我们可以用 = 进行赋值操作,== 进行比较,+ 做串联(是不是很简单?)。我们尽可以把它看成是C++的基本数据类型。 首先,为了在我们的程序中使用string类型,我们必须包含头文件 。如下: #include //注意这里不是string.h string.h是C字符串头文件 1.声明一个C++字符串 声明一个字符串变量很简单: string Str; 这样我们就声明了一个字符串变量,但既然是一个类,就有构造函数和析构函数。上面的声明没有传入参数,所以就直接使用了string的默认的构造函数,这个函数所作的就是把Str 初始化为一个空字符串。String类的构造函数和析构函数如下: a) string s; //生成一个空字符串s b) string s(str) //拷贝构造函数生成str的复制品 c) string s(str,stridx) //将字符串str内"始于位置stridx"的部分当作字符串的初值 d) string s(str,stridx,strlen) //将字符串str内"始于stridx且长度顶多strlen"的部分作为字符串的初值 e) string s(cstr) //将C字符串作为s的初值 f) string s(chars,chars_len) //将C字符串前chars_len个字符作为字符串s的初值。 g) string s(num,c) //生成一个字符串,包含num个c字符 h) string s(beg,end) //以区间beg;end(不包含end)内的字符作为字符串s的初值 i) s.~string() //销毁所有字符,释放内存 都很简单,我就不解释了。 2.字符串操作函数 这里是C++字符串的重点,我先把各种操作函数罗列出来,不喜欢把所有函数都看完的人可以在这里找自己喜欢的函数,再到后面看他的详细解释。 a) =,assign() //赋以新值 b) swap() //交换两个字符串的内容 c) +=,append(),push_back() //在尾部添加字符 d) insert() //插入字符 e) erase() //删除字符 f) clear() //删除全部字符 g) replace() //替换字符 h) + //串联字符串 i) ==,!=,<,<=,>,>=,compare() //比较字符串 j) size(),length() //返回字符数量 k) max_size() //返回字符的可能最大个数 l) empty() //判断字符串是否为空 m) capacity() //返回重新分配之前的字符容量

Java中string的相关函数

Java中string的相关函数 字串与字元 文字字串是一个相当基本且经常被使用到的资料型态,然而在Java 中字串不象char、int 与float 一样是个基本资料型态,而是使用https://www.360docs.net/doc/817107364.html,ng.String 类别来加以表示,该类别定义了许多有用的方法来操作字串。String 物件是固定不变的(immutable):一旦一个String 物件被建立了,则没有任何方法可以改变它所代表的文字,因此,每个运作字串的方法会传回一个新的String 物件,而所修正过后的字串便是储存在此新物件里。 以下的程式码展示了你可以对字串所执行的运作: // 建立字串 String s = "Now "; // String 物件有个特殊的写法 String t = s + "is the time. "; // 使用+ 运算子来串连字串 String t1 = s + " " + 23.4; // + 将其它值转换为字串 t1 = String.valueOf( 'c '); // 从字元值获得对应的字串 t1 = String.valueOf(42); // 获得整数或其他任何数值的字串版本 t1 = Object.toString(); // 使用toString() 将物件转换为字串 // 字串长度 int len = t.length(); // 字串中的字元数:16 // 字串中的子字串 String sub = t.substring(4); // 传回从char 4 到最后的子字串:"is the time. " sub = t.substring(4, 6); // 传回chars 4 与5:"is " sub = t.substring(0, 3); // 传回chars 0 到2:"Now " sub = t.substring(x, y); // 传回从位置x 到y-1 间的子字串 int numchars = sub.length(); // 子字串的长度永远是(y-x) // 从一个字串中撷取(extract)出字元 char c = t.charAt(2); // 取得t 的第三个字元:w char[] ca = t.toCharArray(); // 将字串转换为一个字元阵列 t.getChars(0, 3, ca, 1); // 将t 中的前三个字元放到ca[1] 到ca[3] 中 // 大小写转换 String caps = t.toUpperCase(); // 转换为大写 String lower = t.toLowerCase(); // 转换为小写 // 字串比较 boolean b1 = t.equals( "hello "); // 传回flase:两字串并不相等 boolean b2 = t.equalsIgnoreCase(caps); // 忽略大小写的字串比较:true boolean b3 = t.startsWith( "Now "); // 传回true boolean b4 = t.endsWith( "time. "); // 传回true int r1 = https://www.360docs.net/doc/817107364.html,pareTo( "Pow "); // 传回值<0:s 在"Pow "之前 int r2 = https://www.360docs.net/doc/817107364.html,pareTo( "Now "); // 传回值0:两字串相等

string的用法

1.声明一个C++字符串 声明一个字符串变量很简单: string Str; 这样我们就声明了一个字符串变量,但既然是一个类,就有构造函数和析构函数。上面的声明没有传入参数,所以就直接使用了string的默认的构造函数,这个函数所作的就是把Str 初始化为一个空字符串。String类的构造函数和析构函数如下: a) string s; //生成一个空字符串s b) string s(str) //拷贝构造函数生成str的复制品 c) string s(str,stridx) //将字符串str内"始于位置stridx"的部分当作字符串的初值 d) string s(str,stridx,strlen) //将字符串str内"始于stridx且长度顶多strlen"的部分作为字符串的初值 e) string s(cstr) //将C字符串作为s的初值 f) string s(chars,chars_len) //将C字符串前chars_len个字符作为字符串s的初值。 g) string s(num,c) //生成一个字符串,包含num个c字符 h) string s(beg,end) //以区间beg;end(不包含end)内的字符作为字符串s的初值 i) s.~string() //销毁所有字符,释放内存 都很简单,我就不解释了。 2.字符串操作函数 这里是C++字符串的重点,我先把各种操作函数罗列出来,不喜欢把所有函数都看完的人可以在这里找自己喜欢的函数,再到后面看他的详细解释。 a) =,assign() //赋以新值 b) swap() //交换两个字符串的内容 c) +=,append(),push_back() //在尾部添加字符 d) insert() //插入字符 e) erase() //删除字符 f) clear() //删除全部字符 g) replace() //替换字符 h) + //串联字符串 i) ==,!=,<,<=,>,>=,compare() //比较字符串 j) size(),length() //返回字符数量 k) max_size() //返回字符的可能最大个数 l) empty() //判断字符串是否为空 m) capacity() //返回重新分配之前的字符容量 n) reserve() //保留一定量内存以容纳一定数量的字符 o) [ ], at() //存取单一字符 p) >>,getline() //从stream读取某值 q) << //将谋值写入stream r) copy() //将某值赋值为一个C_string s) c_str() //将内容以C_string返回 t) data() //将内容以字符数组形式返回 u) substr() //返回某个子字符串

Android的String用法

String : 字符串类型 一、构造函数 String(byte[ ]bytes):通过byte数组构造字符串对象。 String(char[ ]value):通过char数组构造字符串对象。 String(Sting original):构造一个original的副本。即:拷贝一个original。 String(StringBuffer buffer):通过StringBuffer数组构造字符串对象。 例如: byte[] b = {'a','b','c','d','e','f','g','h','i','j'}; char[] c = {'0','1','2','3','4','5','6','7','8','9'}; String sb = new String(b); //abcdefghij String sb_sub = new String(b,3,2); //de String sc = new String(c); //0123456789 String sc_sub = new String(c,3,2); //34 String sb_copy = new String(sb); //abcdefghij System.out.println("sb:"+sb); System.out.println("sb_sub:"+sb_sub); System.out.println("sc:"+sc); System.out.println("sc_sub:"+sc_sub); System.out.println("sb_copy:"+sb_copy); 输出结果:sb:abcdefghij sb_sub:de sc:0123456789 sc_sub:34 sb_copy:abcdefghij 二、方法: 说明:①、所有方法均为public。 ②、书写格式:[修饰符] <返回类型><方法名([参数列表])> 例如:static int parseInt(String s) 表示此方法(parseInt)为类方法(static),返回类型为(int),方法所需要为String类型。 1. char charAt(int index):取字符串中的某一个字符,其中的参数index指的是字符串中序数。字符串的序数从0开始到length()-1 。 例如:String s = new String("abcdefghijklmnopqrstuvwxyz"); System.out.println("s.charAt(5): " + s.charAt(5) ); 结果为:s.charAt(5): f 2.int compareTo(String anotherString):当前String对象与anotherString比较。相等关系返回0;不相等时,从两个字符串第0个字符开始比较,返回第一个不相等的字符差,另一种情况,较长字符串的前面部分恰巧是较短的字符串,返回它们的长度差。 3. int compareTo(Object o) :如果o是String对象,和2的功能一样;否则抛出ClassCastException异常。 例如:String s1 = new String("abcdefghijklmn"); String s2 = new String("abcdefghij"); String s3 = new String("abcdefghijalmn"); System.out.println("https://www.360docs.net/doc/817107364.html,pareTo(s2): " + https://www.360docs.net/doc/817107364.html,pareTo(s2) ); //返回长度差

String常见的操作和方法

String常见的操作和方法 String类适用于描述字符串事物 那么它就提供了多个方法对字符串进行操作。 常见的操作有哪些? “afbs” 1、获取 1.1 字符串中包含的字符数,也就是字符串的长度。 int length(): 获取长度。 1.2 根据位置获取位置上某个字符。 char charAt(int index): 1.3 根据字符获取字符在字符串中位置。 int indexOf(int ch): 返回的是ch在字符串中第一次出现的位置。 int indexOf(int ch, int fromIndex): 从fromIndex指定位置开始,获取ch在字符串中出现的位置。 int indexOf(int str): 返回的是str在字符串中第一次出现的位置。 int indexOf(int str, int fromIndex): 从fromIndex指定位置开始,获取str在字符串中出现的位置。 int lastIndexOf(int ch); 2、判断。 2.1 字符串中是否包含某一个子串。 boolean contains(str): 特殊之处:indexOf(str):可以索引str第一次出现的位置,如果返回-1.表示该str不存在字符串中。 所以,也可以用于对指定判断是否包含。 if(str.indexOf("aa")!=-1) 而且该方法既可以判断,又可以获取出现的位置。 2.2 字符串中是否有内容。

boolean ifEmpty(): 原理就是判断长度是否为0. 2.3 字符串是否是以指定内容开头。 boolean startsWith(str); 2.4 字符串是否是以指定内容结尾。 boolean endsWith(str); 2.5判断字符串内容是否相同。复写了Object类中的equals方法。boolean equals(str); 2.6判断内容是否相同,并忽略大小写。 boolean equalsIgnoreCase(); 3、转换 3.1 将字符数组转成字符串。 构造函数:String(char[]) String(char[],offset,count):将字符数组中的一部分转成字符串。 静态方法: static String copyValueOf(char[]); static String copyValueOf(char[] data,int offset,int count) static String valueOf(char[]): 3.2 将字符串转成字符数组。 char[] toCharArray(): 3.3 将字节数组转成字符串。 String(byte[]) String(byte[],offset,count):将字节数组中的一部分转成字符串。 3.4 将字符串转成字节数组。** byte[] getBytes(): 3.5 将基本数据类型转成字符串。 static String valueOf(int) static String valueOf(double) 3+"";//String.valueOf(3); 特殊:字符串和字节数组在转换过程中,是可以指定编码表的。

C 中的STRING用法

#include//注意是,不是,带.h的是C语言中的头文件using std::string; using std::wstring; 或 using namespace std; 下面你就可以使用string/wstring了,它们两分别对应着char和wchar_t。 string和wstring的用法是一样的,以下只用string作介绍: string类的构造函数: string(const char*s);//用c字符串s初始化 string(int n,char c);//用n个字符c初始化 此外,string类还支持默认构造函数和复制构造函数,如string s1;string s2="hello";都是正确的写法。当构造的string太长而无法表达时会抛出length_error异常; string类的字符操作: const char&operator[](int n)const; const char&at(int n)const; char&operator[](int n); char&at(int n); operator[]和at()均返回当前字符串中第n个字符的位置,但at函数提供范围检查,当越界时会抛出out_of_range异常,下标运算符[]不提供检查访问。 const char*data()const;//返回一个非null终止的c字符数组 const char*c_str()const;//返回一个以null终止的c字符串 int copy(char*s,int n,int pos=0)const;//把当前串中以pos开始的n个字符拷贝到以s为起始位置的字符数组中,返回实际拷贝的数目 string的特性描述: int capacity()const;//返回当前容量(即string中不必增加内存即可存放的元素个数)int max_size()const;//返回string对象中可存放的最大字符串的长度 int size()const;//返回当前字符串的大小 int length()const;//返回当前字符串的长度 bool empty()const;//当前字符串是否为空 void resize(int len,char c);//把字符串当前大小置为len,并用字符c填充不足的部分string类的输入输出操作: string类重载运算符operator>>用于输入,同样重载运算符operator<<用于输出操作。函数getline(istream&in,string&s);用于从输入流in中读取字符串到s中,以换行符'\n'分开。

相关文档
最新文档