需求:有一个随机字符串例如:No.96 HongXing East Road Jining Shandong China.共47的字符,也可能是100或更多个字符组成的字符串。需要将这个字符串截取成最大值为30的字符数组,但要求单词不能被截断!!!
效果应该如下:
字符串1:No.96 HongXing East Road
字符串2:Jining Shandong China.这个问题想的好久,我也没想出一个好的办法,恳求高手帮助一下,谢谢,在线等!!!
效果应该如下:
字符串1:No.96 HongXing East Road
字符串2:Jining Shandong China.这个问题想的好久,我也没想出一个好的办法,恳求高手帮助一下,谢谢,在线等!!!
大致应该是这样,至于代码感觉还是楼主自己写好一些。
不过有个问题,如果出现连在一起超过30个字符的,怎么办?呵呵
string[] strs = text.split(' ');
晚上写写看看
看看能不能写出一个好的函数来
谢谢小刀可乐!!!
static void Main(string[] args)
{
string s = "No.96 HongXing East Road Jining Shandong China";
List<string> ls = new List<string>();
for (int i = 0; i < s.LastIndexOf(" ")+1;)
{
int count = 0,index = i;
for (int j = i; count <=30 && j < s.Length; j++)
{
if (s[j] == ' ') index = j;//小于30的最后一个空格
count++;
}
if(index < s.Length)
ls.Add(s.Substring(i,(index-i)+1));//(index-i)+1是子字符串的长度
i = index+1;
}
ls.ToArray();//已经成功分离了
}
using System.Collections.Generic;
using System.Text;namespace ConsoleApplication1
{
class Program
{ private static int stringLeng = 30; static void Main(string[] args)
{
string a = "No.96 HongXing East Road Jining Shandong China.";
List<string> list = new List<string>();
NewMethod1(a, list);
foreach (string s in list)
{
System.Console.WriteLine(s+" length:"+s.Length.ToString() );
} Console.ReadLine(); } private static string NewMethod1(string a, List<string> list)
{
string l;
string b; while (a.Length > 0)
{ if (a.Length >= stringLeng+1)
{
b = a.Substring(0, stringLeng+1);
l = NewMethod(b, list);
a = l + a.Substring(stringLeng+1);
}
else
{
list.Add(a);
a = string.Empty; } }
return a;
} private static string NewMethod(string b, List<string> list)
{
string l=string.Empty;
for (int i = stringLeng; i > 0; i--)
{
char c = b[i];
if (c ==' ')
{
list.Add(b.Substring(0, i ));
l = b.Substring(i+1);
break;
}
}
return l;
}
}
}
{
string temp="";
string tempf="";
string tempb="";
string tempk="";
if (s.Length>30)
{temp=s.Substring(0,30);
tempf=s.Substring(29,1);
tempb=s.Substring(30,1);
if((tempf=="")||(tempb==""))
{
arr.Add(temp);
s=s.Substring(31);
}
else
{
tempk=s.Substring(0,temp.LastIndexOf(" "));
s=s.Substring(tempk.Length+1);
arr.Add(tempk);
}
getvalue(s);
}
else
{
arr.Add(s);
}
}
大致应该是这样,至于代码感觉还是楼主自己写好一些。
不过有个问题,如果出现连在一起超过30个字符的,怎么办?呵呵思路一样.
你的方法只要在整个字符串后加一个空格即可不好意思,昨天请假了,没来看帖子
今天看到这么多网友回帖
真的很高兴
谢谢大家了
判断一下字符串的长度,如果大于30,则先截取前30个字符,然后对前30个字符的最后一个" "空格进行index()一下,即读取它的位置i,然后根据位置i来截取第一个字符串。然后再对剩下的字符串进行同样方式截取字符串。(同样需要先判断一下剩下字符串的个数是否大于30)依次,知道剩下的字符串个数不大于30位置。如果不大于30,则直接赋值,不需要截取。
static void Main(string[] args)
{
string s = "No.96 HongXing East Road Jining Shandong China ";
List<string> ls = new List<string>();
for (int i = 0; i < s.Length; )
{
int j=0;
int index = 0;
for (; j < 30 && i+j < s.Length; j++)
{
if (s[i+j] == ' ') index = i+j;//小于30的最后一个空格
}
if (j + i > index && j + i < s.Length)
{
ls.Add(s.Substring(i, (index - i) + 1));
i = index + 1; }
else
{
ls.Add(s.Substring(i, j));
i = j+i;
}
}
string[] newStr = ls.ToArray();//已经成功分离了
}
//原算法的错误出在结束的位置,它会少分割一个单词