如何将一部分字符串复制到另一个字符串中 [英] how to copy a part of string into another string
本文介绍了如何将一部分字符串复制到另一个字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用此代码复制包含年份的字符串的最后一部分...
所以我可以计算年龄...
string DOB =10/10/1992
string Year =;
int j = 0;
for(int i = 5; i< 10; i ++)
{
year [j] = DOB [i]; //错误
j ++;
}
解决方案
不 - 你做不到因为字符串是immutable
,它会测量一旦创建了一个字符串,就无法以任何方式更改它。如果要提取字符串的一部分,则需要从现有字符串中创建一个新字符串:
string DOB = 10/10/1992;
string year = DOB.Substring( 6 , 4 跨度>);
或者更好,将日期解析为DateTime,然后从中得到年份:
string DOB = 10/10/1992 跨度>;
DateTime dob = DateTime.Parse(DOB);
string year = dob.Year.ToString();
当用户输入日期时,它可以更灵活地工作,因为它处理的日期格式比明确的子字符串更多。
string DOB = 10/10/1992
datetime DOB = datetime.parse(dob.tostring());
int year = DOB.year;
Year = DOB.Split(' /')。Last();
i'm trying this code to copy last part on string which contain year...
so i would be able to calculat age from this...
string DOB = "10/10/1992"
string Year = "";
int j=0;
for(int i = 5 ; i < 10 ; i ++)
{
year[j]=DOB[i];// error
j++;
}
解决方案
No - you can't do that, because strings areimmutable
, which measn that once a string has been created, you cannot change it in any way. If you want to extract part of a string, then you need to create a new string from the existing one:
string DOB = "10/10/1992"; string year = DOB.Substring(6, 4);
Or better, parse the date into a DateTime, and then get the year from that:
string DOB = "10/10/1992"; DateTime dob = DateTime.Parse(DOB); string year = dob.Year.ToString();This works more flexibly, when the user can enter dates as it copes with more date formats than an explicit substring.
string DOB = "10/10/1992" datetime DOB= datetime.parse(dob.tostring()); int year=DOB.year;
Year = DOB.Split('/').Last();
这篇关于如何将一部分字符串复制到另一个字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文