猿问

c#要怎么样才能这样提取字符串?

<1,a,a,a,a,s,d,we><q,we,e,e,r,
这个是第一条数据,第二条数据d,d,e,f,c,><ahheiuheikuhfkhkn
第三条数据fgrejjkfjgjr,dfg,wef,wef><dsd,df,efr,grt,>
一条完整数据是以<>开头和结束的
如 1.<1,a,a,a,a,s,d,we>
2.<q,we,e,e,r,d,d,e,f,c,>
3.<ahheiuheikuhfkhknfgrejjkfjgjr,dfg,wef,wef>
4.<dsd,df,efr,grt,>
c#要怎么样才能这样提取字符串
数据是 string i;可是i是socket传回来的数据流 每传一次就是一条数据

慕慕森
浏览 129回答 3
3回答

梵蒂冈之花

string s = string.Empty;while(true){int i = str.IndexOf("><",0); //str是你的数据,在while循环外初始化它if(i>0){s = str.Substring(0,i);str = str.Remove(0,i);// 这里s 就是你想要的单个数据,在这里把它打印或其它处理}else{// 这里 str 也是你想要的单个数据,这是最后一条,在这里把它打印或其它处理return;}}这是我的想法,先获取“><”所在索引,然后截取出来,并在源数据中将截取出的部分删除掉,最后获取不到“><”的索引,表示是最后一条数据了,不知道能不能实现,你自己试下,或等等看别人还有什么好方法

MMMHUHU

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{class Program{static void Main(string[] args){string input1 = "<1,a,a,a,a,s,d,we><q,we,e,e,r,";string input2 = "d,d,e,f,c,><ahheiuheikuhfkhkn";string input3 = "fgrejjkfjgjr,dfg,wef,wef><dsd,df,efr,grt,>";bool validate = StringConverter.ValidateTagIsClose(input1, input2, input3);if (validate){List<string> myString = StringConverter.GetConvertString(input1, input2, input3);foreach (string str in myString){Console.WriteLine(str);}}else{Console.WriteLine("开始标记和结束标记不成对!");}Console.ReadKey();}}public static class StringConverter{public static char startTag = '<';public static char endTage = '>';public static List<string> GetConvertString(params string[] input){List<string> outResult = new List<string>();string completeString = string.Empty;foreach (string str in input){completeString += str;}char[] completeChars = completeString.ToCharArray();List<int> startTagIndexs = new List<int>();List<int> endTagIndexs = new List<int>();for (int i = 0; i < completeChars.Length; i++){if (completeChars[i].CompareTo(startTag) == 0){startTagIndexs.Add(i);}if (completeChars[i].CompareTo(endTage) == 0){endTagIndexs.Add(i);}}for (int j = 0; j < startTagIndexs.Count; j++){int startTagIndex = startTagIndexs[j];int endTagIndex = endTagIndexs[j];outResult.Add(completeString.Substring(startTagIndex,endTagIndex-startTagIndex+1));}return outResult;}/// <summary>/// 验证标记是否完整关闭,也就是说如果存在一个‘<’,则必须存在一个‘>’/// </summary>/// <param name="input"></param>/// <returns></returns>public static bool ValidateTagIsClose(params string[] input){string completeString = string.Empty;foreach (string str in input){completeString += str;}char[] inputChars = completeString.ToCharArray();int tagCount = 0;foreach (char c in inputChars){if (c.CompareTo(startTag) == 0 || c.CompareTo(endTage) == 0){tagCount += 1;}}if (tagCount % 2 == 0)return true;elsereturn false;}}}

人到中年有点甜

var a="<1,a,a,a,a,s,d,we><q,we,e,e,r,";var b="d,d,e,f,c,><ahheiuheikuhfkhkn";var c="fgrejjkfjgjr,dfg,wef,wef><dsd,df,efr,grt,>";var html=a+b+c;const string pattern = @"<.*?>";var regex = new Regex(pattern);var matches = regex.Matches(html);foreach(var value in matches){//value.ToString()就是你想要的}
随时随地看视频慕课网APP
我要回答