Rambler's Top100
Главная
Новости
Статьи
Форумы
Книги
Коды
Сообщество
Блоги
О нас
 

Логин

Email:
  Пароль:

Войти
Зарегистрироваться
Забыл пароль

Поиск

 Искать :
 
Вперед

Книги по теме

Искать:
в:
Порядок:

Исходник

Автор:

Max Pro

 
Название:

Функция, выдающая количество чисел в тексте и сами числа в виде массива. Язык VC#.NET 2003.

Дата: 14 September 2005
Описание: Хотите прикольнутся и узнать сколько чисел в газетной статье, электронной книге, html-содержимом страницы? Тогда эта функция для Вас. Дано описание функции и пример использования на Windows-форме. 
  Разместить ссылку на этот исходник в форуме вы можете вставив в текст сообщения следующую строку: [CODEPOST ID=164]Функция, выдающая количество чисел в тексте и сами числа в виде массива. Язык VC#.NET 2003.[/CODEPOST]
Оценка: Проголосовало 5 посетителей, средняя оценка 2.00
Оценить:
  1 /*Вот сама функция*/
  2 		/* Функция, выдающая количество чисел в тексте и сами числа в виде массива. Переваривает любые типы
  3 		 * Интеллект такой: распознаются плюсы, минусы, десятичные точки и запятые, пробелы игнорируются
  4 		 *///если =-1, то объект=null или dbnull
  5 		public static Int32 iNumFromStr(Object oObject,out Decimal[] oArray)
  6 		{
  7 			if(IsNull(oObject))
  8 			{
  9 				oArray=new Decimal[0];
 10 				return -1;
 11 			}
 12 			//var
 13 			String sObject=Convert.ToString(oObject);
 14 			String s="";
 15 			String sNum="";
 16 			String sTemp="";
 17 			Int32 i=0;
 18 			Int32 j=0;
 19 			Int32 iMax=sObject.Length-1;
 20 			Int32 iNum=0;
 21 			Int32 iMinus=1;
 22 			Boolean bNum=false;
 23 			Boolean bPoint=false;
 24 			System.Collections.ArrayList oCol=new System.Collections.ArrayList();
 25 			//end var
 26 			for(i=0;i<=iMax;i++)
 27 			{
 28 				s=sObject.Substring(i,1);
 29 				if(s!=" ")
 30 				{
 31 					if(IsNumeric(s)) bNum=true;
 32 					if((bNum==false && s=="+") || (bNum==false && s=="-") || (bPoint==false && s==".") || (bPoint==false && s==",") || IsNumeric(s))
 33 					{
 34 						if(s=="." || s==",") bPoint=true;
 35 						sNum+=s;
 36 					}
 37 					else
 38 					{
 39 						if(sNum!="")
 40 						{
 41 							sTemp=sNum;
 42 							for(j=0;j<=sTemp.Length-1;j++)
 43 							{
 44 								s=sTemp.Substring(j,1);
 45 								if(s=="+")
 46 								{
 47 									sNum=sNum.Remove(0,1);
 48 								}
 49 								else if(s=="-")
 50 								{
 51 									sNum=sNum.Remove(0,1);
 52 									iMinus*=-1;
 53 								}
 54 							}
 55 							if(IsNumeric(sNum.Replace(".",",")))
 56 							{
 57 								sNum=sNum.Replace(".",",");
 58 								oCol.Add(Convert.ToDecimal(sNum)*iMinus);
 59 							}
 60 							else if(IsNumeric(sNum.Replace(",",".")))
 61 							{
 62 								sNum=sNum.Replace(",",".");
 63 								oCol.Add(Convert.ToDecimal(sNum)*iMinus);
 64 							}
 65 							sNum="";
 66 							bNum=false;
 67 							bPoint=false;
 68 							iMinus=1;
 69 						}//end if(sNum!="")
 70 					}//end else if((bNum==false && s=="+") || (bNum==false && s=="-") || (bPoint==false && s==".") || (bPoint==false && s==",") || IsNumeric(s))
 71 				}//end if(s!=" ")
 72 			}//end for(i=0;i<=iMax;i++)
 73 			if(sNum!="")
 74 			{
 75 				sTemp=sNum;
 76 				for(j=0;j<=sTemp.Length-1;j++)
 77 				{
 78 					s=sTemp.Substring(j,1);
 79 					if(s=="+")
 80 					{
 81 						sNum=sNum.Remove(0,1);
 82 					}
 83 					else if(s=="-")
 84 					{
 85 						sNum=sNum.Remove(0,1);
 86 						iMinus*=-1;
 87 					}
 88 				}
 89 				if(IsNumeric(sNum.Replace(".",",")))
 90 				{
 91 					sNum=sNum.Replace(".",",");
 92 					oCol.Add(Convert.ToDecimal(sNum)*iMinus);
 93 				}
 94 				else if(IsNumeric(sNum.Replace(",",".")))
 95 				{
 96 					sNum=sNum.Replace(",",".");
 97 					oCol.Add(Convert.ToDecimal(sNum)*iMinus);
 98 				}
 99 			}//end if(sNum!="")
100 			iNum=oCol.Count;
101 			oArray=new Decimal[iNum];
102 			for(i=0;i<=iNum-1;i++)
103 			{
104 				oArray[i]=Convert.ToDecimal(oCol[i]);
105 			}
106 			return iNum;
107 		}
108 
109 /*Вспомогательные функции IsNull и IsNumeric приведены в примере ниже*/
110 
111 /*Фотографию примера смотри по адресу http://aspnetmania.com/Forums/ForumMessage/file.aspx?ID=491*/
112 
113 /*А вот пример использования на Windows Form (сделан для испытания)*/
114 using System;
115 using System.Drawing;
116 using System.Collections;
117 using System.ComponentModel;
118 using System.Windows.Forms;
119 using System.Data;
120 
121 namespace WindowsApplication2
122 {
123 	/// <summary>
124 	/// Summary description for Form1.
125 	/// </summary>
126 	public class Form1 : System.Windows.Forms.Form
127 	{
128 		private System.Windows.Forms.Label label1;
129 		private System.Windows.Forms.TextBox textBox1;
130 		private System.Windows.Forms.Label label2;
131 		private System.Windows.Forms.TextBox textBox2;
132 		private System.Windows.Forms.Button button1;
133 		private System.Windows.Forms.ListBox listBox1;
134 		/// <summary>
135 		/// Required designer variable.
136 		/// </summary>
137 		private System.ComponentModel.Container components = null;
138 
139 		public Form1()
140 		{
141 			//
142 			// Required for Windows Form Designer support
143 			//
144 			InitializeComponent();
145 
146 			//
147 			// TODO: Add any constructor code after InitializeComponent call
148 			//
149 		}
150 
151 		/// <summary>
152 		/// Clean up any resources being used.
153 		/// </summary>
154 		protected override void Dispose( bool disposing )
155 		{
156 			if( disposing )
157 			{
158 				if (components != null) 
159 				{
160 					components.Dispose();
161 				}
162 			}
163 			base.Dispose( disposing );
164 		}
165 
166 		#region Windows Form Designer generated code
167 		/// <summary>
168 		/// Required method for Designer support - do not modify
169 		/// the contents of this method with the code editor.
170 		/// </summary>
171 		private void InitializeComponent()
172 		{
173 			this.label1 = new System.Windows.Forms.Label();
174 			this.textBox1 = new System.Windows.Forms.TextBox();
175 			this.label2 = new System.Windows.Forms.Label();
176 			this.textBox2 = new System.Windows.Forms.TextBox();
177 			this.button1 = new System.Windows.Forms.Button();
178 			this.listBox1 = new System.Windows.Forms.ListBox();
179 			this.SuspendLayout();
180 			// 
181 			// label1
182 			// 
183 			this.label1.Location = new System.Drawing.Point(0, 8);
184 			this.label1.Name = "label1";
185 			this.label1.Size = new System.Drawing.Size(88, 16);
186 			this.label1.TabIndex = 0;
187 			this.label1.Text = "Введите текст";
188 			// 
189 			// textBox1
190 			// 
191 			this.textBox1.Location = new System.Drawing.Point(0, 24);
192 			this.textBox1.Multiline = true;
193 			this.textBox1.Name = "textBox1";
194 			this.textBox1.Size = new System.Drawing.Size(288, 72);
195 			this.textBox1.TabIndex = 1;
196 			this.textBox1.Text = "textBox1";
197 			// 
198 			// label2
199 			// 
200 			this.label2.Location = new System.Drawing.Point(0, 128);
201 			this.label2.Name = "label2";
202 			this.label2.Size = new System.Drawing.Size(120, 16);
203 			this.label2.TabIndex = 2;
204 			this.label2.Text = "Смотрите результат";
205 			// 
206 			// textBox2
207 			// 
208 			this.textBox2.Location = new System.Drawing.Point(0, 144);
209 			this.textBox2.Name = "textBox2";
210 			this.textBox2.Size = new System.Drawing.Size(288, 20);
211 			this.textBox2.TabIndex = 3;
212 			this.textBox2.Text = "textBox2";
213 			// 
214 			// button1
215 			// 
216 			this.button1.Location = new System.Drawing.Point(0, 104);
217 			this.button1.Name = "button1";
218 			this.button1.TabIndex = 4;
219 			this.button1.Text = "Сделать";
220 			this.button1.Click += new System.EventHandler(this.button1_Click);
221 			// 
222 			// listBox1
223 			// 
224 			this.listBox1.Location = new System.Drawing.Point(0, 168);
225 			this.listBox1.Name = "listBox1";
226 			this.listBox1.Size = new System.Drawing.Size(288, 160);
227 			this.listBox1.TabIndex = 6;
228 			// 
229 			// Form1
230 			// 
231 			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
232 			this.ClientSize = new System.Drawing.Size(288, 333);
233 			this.Controls.Add(this.listBox1);
234 			this.Controls.Add(this.button1);
235 			this.Controls.Add(this.textBox2);
236 			this.Controls.Add(this.label2);
237 			this.Controls.Add(this.textBox1);
238 			this.Controls.Add(this.label1);
239 			this.Name = "Form1";
240 			this.Text = "Испытание функции iNumFromStr";
241 			this.Load += new System.EventHandler(this.Form1_Load);
242 			this.ResumeLayout(false);
243 
244 		}
245 		#endregion
246 
247 		/// <summary>
248 		/// The main entry point for the application.
249 		/// </summary>
250 		[STAThread]
251 		static void Main() 
252 		{
253 			Application.Run(new Form1());
254 		}
255 
256 		private void button1_Click(object sender, System.EventArgs e)
257 		{
258 			//var
259 			Decimal[] oArray;
260 			Int32 iNum=iNumFromStr(textBox1.Text,out oArray);
261 			Int32 i=0;
262 			//end var
263 			textBox2.Text="";
264 			textBox2.Text="Обнаружено "+iNum+" чисел.";
265 			listBox1.Items.Clear();
266 			for(i=0;i<=iNum-1;i++)
267 			{
268 				listBox1.Items.Add(oArray[i]);
269 			}
270 		}
271 
272 		// Функция IsNull как в VB6, переваривает любые типы
273 		public static Boolean IsNull(Object oObject)
274 		{
275 			if(oObject==null || oObject==DBNull.Value) return true; else return false;
276 		}
277 		// Функция IsNumeric, переваривает любые типы
278 		public static Boolean IsNumeric(Object oObject)
279 		{
280 			if(IsNull(oObject)) return false;
281 			try//проверка на число
282 			{
283 				Convert.ToDecimal(oObject);
284 				return true;
285 			}
286 			catch
287 			{
288 				return false;
289 			}
290 		}
291 		/* Функция, выдающая количество чисел в строке и сами числа в виде массива. Переваривает любые типы
292 		 * Интеллект такой: распознаются плюсы, минусы, десятичные точки и запятые, пробелы игнорируются
293 		 *///если =-1, то объект=null или dbnull
294 		public static Int32 iNumFromStr(Object oObject,out Decimal[] oArray)
295 		{
296 			if(IsNull(oObject))
297 			{
298 				oArray=new Decimal[0];
299 				return -1;
300 			}
301 			//var
302 			String sObject=Convert.ToString(oObject);
303 			String s="";
304 			String sNum="";
305 			String sTemp="";
306 			Int32 i=0;
307 			Int32 j=0;
308 			Int32 iMax=sObject.Length-1;
309 			Int32 iNum=0;
310 			Int32 iMinus=1;
311 			Boolean bNum=false;
312 			Boolean bPoint=false;
313 			System.Collections.ArrayList oCol=new System.Collections.ArrayList();
314 			//end var
315 			for(i=0;i<=iMax;i++)
316 			{
317 				s=sObject.Substring(i,1);
318 				if(s!=" ")
319 				{
320 					if(IsNumeric(s)) bNum=true;
321 					if((bNum==false && s=="+") || (bNum==false && s=="-") || (bPoint==false && s==".") || (bPoint==false && s==",") || IsNumeric(s))
322 					{
323 						if(s=="." || s==",") bPoint=true;
324 						sNum+=s;
325 					}
326 					else
327 					{
328 						if(sNum!="")
329 						{
330 							sTemp=sNum;
331 							for(j=0;j<=sTemp.Length-1;j++)
332 							{
333 								s=sTemp.Substring(j,1);
334 								if(s=="+")
335 								{
336 									sNum=sNum.Remove(0,1);
337 								}
338 								else if(s=="-")
339 								{
340 									sNum=sNum.Remove(0,1);
341 									iMinus*=-1;
342 								}
343 							}
344 							if(IsNumeric(sNum.Replace(".",",")))
345 							{
346 								sNum=sNum.Replace(".",",");
347 								oCol.Add(Convert.ToDecimal(sNum)*iMinus);
348 							}
349 							else if(IsNumeric(sNum.Replace(",",".")))
350 							{
351 								sNum=sNum.Replace(",",".");
352 								oCol.Add(Convert.ToDecimal(sNum)*iMinus);
353 							}
354 							sNum="";
355 							bNum=false;
356 							bPoint=false;
357 							iMinus=1;
358 						}//end if(sNum!="")
359 					}//end else if((bNum==false && s=="+") || (bNum==false && s=="-") || (bPoint==false && s==".") || (bPoint==false && s==",") || IsNumeric(s))
360 				}//end if(s!=" ")
361 			}//end for(i=0;i<=iMax;i++)
362 			if(sNum!="")
363 			{
364 				sTemp=sNum;
365 				for(j=0;j<=sTemp.Length-1;j++)
366 				{
367 					s=sTemp.Substring(j,1);
368 					if(s=="+")
369 					{
370 						sNum=sNum.Remove(0,1);
371 					}
372 					else if(s=="-")
373 					{
374 						sNum=sNum.Remove(0,1);
375 						iMinus*=-1;
376 					}
377 				}
378 				if(IsNumeric(sNum.Replace(".",",")))
379 				{
380 					sNum=sNum.Replace(".",",");
381 					oCol.Add(Convert.ToDecimal(sNum)*iMinus);
382 				}
383 				else if(IsNumeric(sNum.Replace(",",".")))
384 				{
385 					sNum=sNum.Replace(",",".");
386 					oCol.Add(Convert.ToDecimal(sNum)*iMinus);
387 				}
388 			}//end if(sNum!="")
389 			iNum=oCol.Count;
390 			oArray=new Decimal[iNum];
391 			for(i=0;i<=iNum-1;i++)
392 			{
393 				oArray[i]=Convert.ToDecimal(oCol[i]);
394 			}
395 			return iNum;
396 		}
397 
398 		private void Form1_Load(object sender, System.EventArgs e)
399 		{
400 		
401 		}
402 	}
403 }
404 
Вернуться к списку исходников в категории Немного оффтопа
 
Наш Киев

Apartments for Rent

Rambler's Top100
Рейтинг@Mail.ru
Идея: Dimon aka Manowar Программирование: Dimon aka Manowar Дизайн: Dan Lebedev
Хостинг от компании Parking.ru
Карта сайта