Advertisement
n4wn4w

C# String

Apr 15th, 2015
382
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 30.30 KB | None | 0 0
  1.        
  2. string allLangs = "Started from the bottom now we're here Started from the bottom now my whole team fucking here Started from the bottom now we're here".ToUpper();
  3.             string[] langs = allLangs.Split(new char[] { ',', ';', ' ','.','!','\'','"','$','?','+' },
  4.                 StringSplitOptions.RemoveEmptyEntries);
  5.            
  6.             string kurr = string.Join("", langs);
  7.             char[] letters = kurr.ToCharArray();
  8.            
  9.             Dictionary<char, int> dict = new Dictionary<char, int>();
  10.  
  11.             foreach (char t in letters)
  12.             {
  13.                 if (!dict.ContainsKey(t))
  14.                 {
  15.                     dict.Add(t, 1);
  16.                 }
  17.                 else
  18.                 {
  19.                     dict[t]++;
  20.                 }
  21.             }
  22.            
  23.  
  24.             dict = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
  25.  
  26.            
  27.             Console.WriteLine("\nLetter occurence table:\n{0}\n",string.Join("\n",
  28.                 dict.Select(x => string.Format(@"'{0}' -> {1,2} {2}", x.Key, x.Value,new string('#',x.Value))).ToArray().Reverse()));
  29.  
  30.            
  31.  
  32.  
  33. ///////////////////////////////////////////////////////
  34.     string str = "SoftUni";
  35.             Console.WriteLine(str);
  36.             for (int i = 0; i < str.Length; i++)
  37.             {
  38.                 Console.WriteLine("str[{0}] = {1}", i, str[i]);
  39.             }
  40.  
  41.             Console.WriteLine(str.IndexOf("Uni")); // 9
  42.             Console.WriteLine(str.IndexOf("uni")); // -1 (not found)
  43.  
  44.             Console.WriteLine(str.Substring(4, 2)); // Un
  45.  
  46.             Console.WriteLine(str.Replace("Soft", "Hard")); // HarUni
  47.  
  48.             Console.WriteLine(str.ToLower()); // softuni
  49.             Console.WriteLine(str.ToUpper()); // SOFTUNI
  50.  
  51.             // This will not compile, because strings are immutable
  52.             // str[5] = 'a';
  53.  
  54.             string firstName = "Steve";
  55.             string lastName = "Jobs";
  56.             int age = 56;
  57.             string nameAndAge = firstName + " " + lastName + " (age: " + age + ")";
  58.             Console.WriteLine(nameAndAge); // Steve Jobs (age: 56)
  59.  
  60.             string allLangs = "C#, Java; HTML, CSS; PHP, JavaScript; SQL";
  61.             string[] langs = allLangs.Split(new char[] { ',', ';', ' ' },
  62.                 StringSplitOptions.RemoveEmptyEntries);
  63.             foreach (var lang in langs)
  64.             {
  65.                 Console.WriteLine(lang);
  66.             }
  67.  
  68.             Console.WriteLine("Langs = " + string.Join(", ", langs));
  69.             string kurr = string.Join(", ", langs);
  70.             char[] kur = kurr.ToCharArray();
  71.  
  72.             Console.WriteLine(kur);
  73.  
  74.           //  Console.WriteLine("  \n\n Software  University $ $$ ".Trim(new char[]{'$'}));
  75.  
  76.  
  77.  
  78.             String header = "  \n\n Software  University $ $$ '' ";
  79.             Console.WriteLine(header);
  80.             Console.WriteLine(header.Trim(new Char[] { ' ', '*', '$' ,'\''}));
  81.  
  82.             string MyString = "  \n\n Software  University  $$ ";
  83.             char[] MyChar = { 't', 'U', 'v', 's', 'y', 'i', ' ','$' };
  84.             string NewString = MyString.TrimEnd(MyChar);
  85.             Console.WriteLine(NewString);
  86.  
  87.  
  88. ////////////////////////////////////////////////////////////  string compare //
  89.  
  90. string[] towns = {"Sofia", "Varna", "Plovdiv",
  91.             "Pleven", "Bourgas", "Rousse", "Stara Zagora",
  92.             "Veliko Tarnovo", "Yambol", "Sliven"};
  93.  
  94.             Array.Sort(towns);
  95.  
  96.             Console.WriteLine(towns[0]);
  97.             string firstTown = towns[0];
  98.             for (int i = 1; i < towns.Length; i++)
  99.             {
  100.                 string currentTown = towns[i];
  101.                 if (String.Compare(currentTown, firstTown) > 0)// sravnqva i dava koi podred ako e <0 shte e burgar ako e >0 shte e yambol
  102.                 {
  103.                     firstTown = currentTown;
  104.                 }
  105.             }
  106.             Console.WriteLine("First town: {0}", firstTown);
  107.  
  108. ///////////////// conkatenacia na string ////////////
  109.  
  110.  string firstName = "Telerik";
  111.         string lastName = "Academy";
  112.  
  113.         string fullName = firstName + " " + lastName;
  114.         Console.WriteLine(fullName);
  115.  
  116.         int age = 25;
  117.  
  118.         string nameAndAge =
  119.             "Name: " + fullName +
  120.             "\nAge: " + age;
  121.         Console.WriteLine(nameAndAge);
  122.  
  123.  
  124. /////////////// searchings INDEXOF  ////////////////////
  125.  
  126.  
  127. string str = "C# Programming Course";
  128.  
  129.         int index = str.IndexOf("C#"); // index = 0
  130.         Console.WriteLine(index);
  131.  
  132.         index = str.IndexOf("Course"); // index = 15
  133.         Console.WriteLine(index);
  134.  
  135.         // IndexOf is case-sensetive. -1 means not found
  136.         index = str.IndexOf("COURSE"); // index = -1
  137.         Console.WriteLine(index);
  138.  
  139.         // Case-insensitive IndexOf
  140.         index = str.ToLower().IndexOf("COURSE".ToLower()); // 18
  141.  
  142.         index = str.IndexOf("ram"); // index = 7
  143.         Console.WriteLine(index);
  144.  
  145.         index = str.IndexOf("r"); // index = 4
  146.         Console.WriteLine(index);
  147.  
  148.         index = str.IndexOf("r", 5); // index = 7
  149.         Console.WriteLine(index);
  150.  
  151.         index = str.IndexOf("r", 8); // index = 18
  152.         Console.WriteLine(index);
  153.  
  154.  
  155. ///////////////////////  drugi operacii  ///////
  156.  
  157.  
  158.   // String.Replace() example
  159.         string cocktail = "Vodka + Martini + Cherry";
  160.         string replaced = cocktail.Replace("+", "and");
  161.         Console.WriteLine(replaced);
  162.  
  163.         // String.Remove() example
  164.         string price = "$ 1234567";
  165.         string lowPrice = price.Remove(2, 3);
  166.         Console.WriteLine(lowPrice);
  167.  
  168.         // Uppercase and lowercase conversion examples
  169.         string alpha = "aBcDeFg";
  170.         string lowerAlpha = alpha.ToLower();
  171.         Console.WriteLine(lowerAlpha);
  172.         string upperAlpha = alpha.ToUpper();
  173.         Console.WriteLine(upperAlpha);
  174.  
  175.         // Trim() example
  176.         string s = "  example of white space ";
  177.         string clean = s.Trim();
  178.         Console.WriteLine(clean);
  179.  
  180.         // Trim(chars) example
  181.         s = " \t\nHello!!! \n";
  182.         clean = s.Trim(' ', ',', '!', '\n', '\t');
  183.         Console.WriteLine(clean);
  184.  
  185.         // TrimStart() example
  186.         s = "   C#   ";
  187.         clean = s.TrimStart();
  188.         Console.WriteLine(clean);
  189.  
  190.         // TrimEnd() example
  191.         s = "   C#   ";
  192.         clean = s.TrimEnd();
  193.         Console.WriteLine(clean);
  194.  
  195. ////////////////  string builder ///////////////////////
  196.  
  197.         public static string ReverseIt(string s)
  198.     {
  199.         StringBuilder sb = new StringBuilder();
  200.         for (int i = s.Length - 1; i >= 0; i--)
  201.         {
  202.             sb.Append(s[i]);
  203.         }
  204.         return sb.ToString();
  205.     }
  206.  
  207.     public static string ExtractCapitals(string s)
  208.     {
  209.         StringBuilder result = new StringBuilder();
  210.         for (int i = 0; i < s.Length; i++)
  211.         {
  212.             char ch = s[i];
  213.             if (Char.IsUpper(ch))
  214.             {
  215.                 result.Append(ch);
  216.             }
  217.         }
  218.         return result.ToString();
  219.     }
  220.  
  221.     public static string DupChar(char ch, int count)
  222.     {
  223.         StringBuilder result = new StringBuilder(count);
  224.         for (int i = 0; i < count; i++)
  225.         {
  226.             result.Append(ch);
  227.         }
  228.         return result.ToString();
  229.     }
  230.  
  231.     static void Main()
  232.     {
  233.         string s = "Telerik Academy";
  234.  
  235.         string reversed = ReverseIt(s);
  236.         Console.WriteLine(reversed);
  237.  
  238.         string capitals = ExtractCapitals(s);
  239.         Console.WriteLine(capitals);
  240.  
  241.         DateTime startTime = DateTime.Now;
  242.         Console.WriteLine("Concatenation 200 000 chars...");
  243.         DupChar('a', 200000);
  244.         DateTime endTime = DateTime.Now;
  245.         Console.WriteLine("... done in {0} seconds", endTime - startTime);
  246.  
  247.  
  248. ///////////////////  formating string /////////////////////
  249.  
  250.  
  251. Console.Write("The current culture is: ");
  252.         Console.WriteLine(System.Threading.Thread.CurrentThread.CurrentCulture);
  253.  
  254.         int number = 42;
  255.         string s = number.ToString("D5"); // 00042
  256.         Console.WriteLine(s);
  257.  
  258.         s = number.ToString("X"); // 2A
  259.         Console.WriteLine(s);
  260.  
  261.         s = number.ToString("x4"); // 002a
  262.         Console.WriteLine(s);
  263.  
  264.         // Chenge the default culture to Bulgarian
  265.        
  266.  
  267.         // Print the currency as Canadian dollars
  268.        
  269.  
  270.         double d = 0.375;
  271.         s = d.ToString("F2"); // 0,38
  272.         Console.WriteLine(s);
  273.  
  274.         s = d.ToString("F10"); // 0,3750000000
  275.         Console.WriteLine(s);
  276.  
  277.         s = d.ToString("P2"); // 37,50 %
  278.         Console.WriteLine(s);
  279.  
  280.         string template = "If I were {0}, I would {1}.";
  281.         string sentence1 = String.Format(
  282.             template, "developer", "know C#");
  283.         Console.WriteLine(sentence1);
  284.         // If I were developer, I would know C#.
  285.  
  286.         string sentence2 = String.Format(
  287.             template, "elephant", "weigh 4500 kg");
  288.         Console.WriteLine(sentence2);
  289.         // If I were elephant, I would weigh 4500 kg.
  290.  
  291.         s = String.Format("{0,10:D}", number); // "        42"
  292.         Console.WriteLine(s);
  293.  
  294.         s = String.Format("{0,10:F5}", d); // "   0,37500"
  295.         Console.WriteLine(s);
  296.  
  297.         Console.WriteLine("Dec {0:D} = Hex {1:X}", number, number);
  298.         // "Dec 42 = Hex 2A"
  299.  
  300.         DateTime now = DateTime.Now;
  301.         Console.WriteLine("Now is {0:d.MM.yyyy HH:mm:ss}.", now);
  302.         // Now is 31.03.2006 08:30:32
  303.  
  304.         // Print the date and time in English (Canada)
  305.        
  306.  
  307.         // Print the date and time in Russian (Russia)
  308.        
  309.        
  310.         Console.WriteLine(1.25); // 1.25 -> the separator will be "." (Invariant)
  311.  
  312.  
  313.  
  314.  
  315. /////////////////////  STRING  HOMEWORKS  ????????///////////////////////////////////////////////////////////////////
  316.  
  317.  
  318.  
  319.  
  320. Problem 2. Reverse string  /////////////////////////////////////////////////////////////////
  321.  
  322.  
  323. string text = "Elrond: Cast it into the fire! Destroy it!";
  324.             char[] charr = text.ToCharArray();
  325.             Array.Reverse(charr);
  326.             Console.WriteLine(charr);
  327.  
  328.  
  329. Problem 3. Correct brackets   ///////////////////////////////////////////////////////////
  330.  
  331. Console.WriteLine("Please enter some expresion: ");
  332.             string expresion = Console.ReadLine();
  333.             int countOpenBracket = 0;
  334.             int countClosedBracket = 0;
  335.             foreach (var ch in expresion)
  336.             {
  337.                 if (ch == '(')
  338.                 {
  339.                     countOpenBracket++;
  340.                 }
  341.                 else if (ch == ')')
  342.                 {
  343.                     countClosedBracket++;
  344.                 }
  345.             }
  346.             if (countOpenBracket == countClosedBracket)
  347.             {
  348.                 Console.WriteLine("Your expression is valid");
  349.             }
  350.             else
  351.             {
  352.                 Console.WriteLine("Your expression is invalid");
  353.             }
  354.  
  355.  
  356. Problem 4. Sub-string in text   ////////////////////////////////////////////////////////////////////////
  357.  
  358. string text = "We are living in an yellow submarine. We don't have anything else. Inside the submarine is very tight. So we are drinking all the day. We will move out of it in 5 days.";
  359.         string pattern = "in"; // ako iskam da mi tursi samo dumata " in " tova e patterna
  360.  
  361.         Console.WriteLine(Regex.Matches(text, pattern, RegexOptions.IgnoreCase).Count);
  362.  
  363.  
  364.  
  365.  
  366. Problem 5. Parse tags  ////////////////////////////////////////////////////////////////////////////
  367.  
  368. /*
  369. 05 You are given a text. Write a program that changes the text in all regions surrounded by the tags <upcase> and </upcase> to uppercase. The tags cannot be nested.
  370. Example:
  371. We are living in a <upcase>yellow submarine</upcase>. We don't have <upcase>anything</upcase> else.
  372. The expected result:
  373. We are living in a YELLOW SUBMARINE. We don't have ANYTHING else.
  374. ОБЯСНЕНИЕ: Задача, чиято цел е да ви сблъска с т.нар. "лакомо" (greedy) съвпадение и "мързеливо" (lazy) съвпадение. В случая машината на регулярните изрази по подразбиране
  375. се опитва да намери най-дългото възможно съвпадение в текста - т.е. първия отварящ и последния затварящ таг. Това се нарича лакомо съвпадение. Решението на проблема е да се използва т.нар. мързеливо съвпадение,
  376. при което се добавя символа "?" след всеки от метасимволите за коли-чество, ние принуждаваме машината на регулярните изрази да приеме първото възможно (съответно и най-кратко) съвпадение.
  377. Използваме Regex.Replace за да  заменим малките букви от текста с големи. След това с ламбда израза (=>) взимаме съдържанието за всеки Match (m) и му правим буквите главни (ToUpper).
  378. */
  379.  
  380. namespace _05_UppercaseTags
  381. {
  382.     class UppercaseTags
  383.     {
  384.         static void Main()
  385.         {
  386.             string text = "We are living in a <upcase>yellow submarine</upcase>. We don't have <upcase>anything</upcase> else.";
  387.  
  388.             Console.WriteLine(Regex.Replace(text, "<upcase>(.*?)</upcase>", m => m.Groups[1].Value.ToUpper()));
  389.         }
  390.  
  391.  
  392.  
  393.  
  394. Problem 6. String length /////////////////////////////////////////////
  395.  
  396. /*
  397. 06 Write a program that reads from the console a string of maximum 20 characters. If the length of the string is less than 20,
  398.  the rest of the characters should be filled with '*'. Print the result string into the console.
  399.  
  400. ОБЯСНЕНИЕ: Лесна задача, за която не са необходими регулярни изрази. Достатъчно е да се използва метода PadRight, които в случая добавя липсващите символи, които остават до 20, със звездички.
  401. */
  402.  
  403. namespace _06_StringOfMax20Characters
  404. {
  405.     class StringOfMax20Characters
  406.     {
  407.         static void Main()
  408.         {
  409.            
  410.             Console.Write("Enter a sequence of characters with max lenght 20: ");
  411.             string text = Console.ReadLine();
  412.  
  413.             if (text.Length <= 20)
  414.             {
  415.                 text = text.PadRight(20, '*');
  416.                 Console.WriteLine(text);
  417.             }
  418.             else
  419.             {
  420.                 Console.WriteLine("The lenght of your string must be max 20.");
  421.             }
  422.         }
  423.  
  424.  
  425.  
  426. Problem 7. Encode/decode //////////////////////////////////
  427.  
  428.             string cipher = Console.ReadLine();
  429.             string str = Console.ReadLine();
  430.  
  431.  
  432.             EncoderDecoder(EncoderDecoder(str, cipher), cipher);
  433.         }
  434.  
  435.         static string EncoderDecoder(string message, string key)
  436.         {
  437.             var strBuilder = new StringBuilder();
  438.             for (int i = 0; i < message.Length; i++)
  439.             {
  440.                 strBuilder.Append((char)(message[i] ^ key[i % key.Length]));
  441.             }
  442.             Console.WriteLine(strBuilder.ToString());
  443.             return strBuilder.ToString();
  444.         }
  445.  
  446.  
  447.  
  448. Problem 8. Extract sentences  ///////////////////////////////////////////
  449.  
  450. using System;
  451. using System.Text.RegularExpressions;
  452.  
  453. /*
  454. 08 Write a program that extracts from a given text all sentences containing given word.
  455. Example: The word is "in". The text is:
  456. We are living in a yellow submarine. We don't have anything else. Inside the submarine is very tight. So we are drinking all the day. We will move out of it in 5 days.
  457. The expected result is:
  458. We are living in a yellow submarine.
  459. We will move out of it in 5 days.
  460. Consider that the sentences are separated by "." and the words – by non-letter symbols.
  461. ОБЯСНЕНИЕ: Трудното тук, както и при повечето задачи с регулярни изрази, е да се измайстори правилно шаблона, по който да се търси. В тази задача дадох име на групата
  462. още в самия шаблон - ?<sentenceName>
  463. */
  464.  
  465. namespace _08_ExtractsFromTextSentences
  466. {
  467.     class ExtractsFromTextSentences
  468.     {
  469.         static void Main()
  470.         {
  471.             string text = "We are living in a yellow submarine. We don't have anything else. Inside the submarine is very tight. So we are drinking all the day. We will move out of it in 5 days.";
  472.             string word = "in";
  473.  
  474.             foreach (Match match in Regex.Matches(text, @"\s*(?<sentenceName>[^\.]*\b" + word + @"\b.*?\.)"))
  475.                 Console.WriteLine(match.Groups["sentenceName"]);
  476.         }
  477.     }
  478. }
  479.  
  480.  
  481.  8 zadacha  2 reshenie /////////////////////////////////////
  482.  
  483. Console.WriteLine("Enter a text:");
  484.         string text = Console.ReadLine();
  485.  
  486.         Console.Write("Enter a word that we are going to looking for in the text: ");
  487.         string word = Console.ReadLine();
  488.  
  489.         string[] sentences = text.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
  490.  
  491.         Console.WriteLine("\nSentences containing word [{0}]:\n", word);
  492.  
  493.         for (int i = 0; i < sentences.Length; i++)
  494.         {
  495.             if (IsSentenceContainsWord(sentences, i, word))
  496.             {
  497.                 Console.WriteLine(sentences[i].Trim() + ".");
  498.             }
  499.         }
  500.  
  501.         Console.WriteLine();
  502.     }
  503.  
  504.     private static bool IsSentenceContainsWord(string[] sentences, int index, string word)
  505.     {
  506.         return Regex.Matches(sentences[index], string.Format(@"\b{0}\b", word), RegexOptions.IgnoreCase).Count != 0;
  507.     }
  508.  
  509.  
  510.  
  511.  
  512.  
  513.  
  514.  
  515. Problem 9. Forbidden words   ///////////////////////////////////////////////////////////////
  516.  
  517. using System;
  518. using System.Text.RegularExpressions;
  519.  
  520. /*
  521. 09 We are given a string containing a list of forbidden words and a text containing some of these words. Write a program that replaces the forbidden words with asterisks.
  522. Example: Microsoft announced its next generation PHP compiler today. It is based on .NET Framework 4.0 and is implemented as a dynamic language in CLR.
  523. Words: "PHP, CLR, Microsoft"
  524. The expected result: ********* announced its next generation *** compiler today. It is based on .NET Framework 4.0 and is implemented as a dynamic language in ***.
  525. ОБЯСНЕНИЕ: С Regex.Replace търсим и заместваме със звезди символите на думите PHP или ("|") или CLR или Microsoft.
  526. */
  527.  
  528. namespace _09_ForbiddenWordsWithAsterisks
  529. {
  530.     class ForbiddenWordsWithAsterisks
  531.     {
  532.         static void Main()
  533.         {
  534.             string text = "Microsoft announced its next generation PHP compiler today. It is based on .NET Framework 4.0 and is implemented as a dynamic language in CLR.";
  535.  
  536.             string forbidWords = @"(\b(PHP|CLR|Microsoft)\b)";
  537.  
  538.             Console.WriteLine(Regex.Replace(text, forbidWords, m => new String('*', m.Length)));
  539.         }
  540.     }
  541. }
  542.  
  543.  
  544.  9 zadacha 2 reshenie//////////////////
  545.  
  546.             Console.WriteLine("Enter a text: ");
  547.             string text = Console.ReadLine();
  548.  
  549.             string[] blackList = { "PHP", "CLR", "Microsoft" };
  550.  
  551.             string regex = string.Format(@"\b({0})\b", string.Join("|", blackList));
  552.  
  553.             Console.WriteLine("Result: \n\n{0}\n", Regex.Replace(text, regex, word => new string('*', word.Length)));
  554.  
  555.  
  556.  
  557.  
  558. Problem 10. Unicode characters   ////////////////////////////////////////////////////////////////
  559.  
  560. using System;
  561. using System.Text.RegularExpressions;
  562. using System.Collections.Generic;
  563.  
  564.  
  565. /*
  566. 10 Write a program that converts a string to a sequence of C# Unicode character literals. Use format strings.
  567. Sample input: "Hi!".
  568. Expected output: "\u0048\u0069\u0021".
  569. ОБЯСНЕНИЕ:
  570. */
  571.  
  572. namespace _10_StringToUnicodeCharacter
  573. {
  574.     class StringToUnicodeCharacter
  575.     {
  576.         static void Main()
  577.         {
  578.             List<int> list = new List<int>();
  579.             string str = Console.ReadLine();
  580.             foreach (var ch in str)
  581.             {
  582.                 list.Add(ch + '\0');
  583.             }
  584.             foreach (var item in list)
  585.             {
  586.                 string result = string.Format("\\u{0:X4}", item);
  587.                 Console.Write(result);
  588.             }
  589.             Console.WriteLine();
  590.         }
  591.     }
  592. }
  593.  
  594.  
  595. Problem 11. Format number   ////////////////////////////////////////////////////////////////////////////////
  596.  
  597. Console.WriteLine("Please enter a nubmer:");
  598.             int number = int.Parse(Console.ReadLine());
  599.             string result = string.Format("{0,15:D}\n{0,15:X4}\n{0,15:P0}\n{0,15:E}", number);
  600.             Console.WriteLine(result);
  601.  
  602.  
  603.  
  604. Problem 12. Parse URL  //////////////////////////////////////////////////////////////////////////
  605.  
  606. Console.WriteLine("Enter URL:");
  607.             string url = Console.ReadLine();
  608.             int index = url.IndexOf("://");
  609.             string protocol = url.Substring(0, index);
  610.             int index1 = url.IndexOf('/', index + 3);
  611.             string server = url.Substring(index + 3, index1 - index - 3);
  612.             string resource = url.Substring(index1);
  613.             Console.WriteLine(protocol);
  614.             Console.WriteLine(server);
  615.             Console.WriteLine(resource);
  616.  
  617.  
  618. 12 zadacha 2 reshenie /////////////////////
  619.  
  620.  
  621. const string URL = @"http://telerikacademy.com/Courses/Courses/Details/212";
  622.         var fragments = Regex.Match(URL, "(.*)://(.*?)(/.*)").Groups;
  623.  
  624.         Console.WriteLine("URL Address: {0}", URL);
  625.         Console.WriteLine("\n[protocol] = {0}", fragments[1]);
  626.         Console.WriteLine("[server] = {0}", fragments[2]);
  627.         Console.WriteLine("[resource] = {0}\n", fragments[3]);
  628.  
  629.  
  630.  
  631. 13 Write a program that reverses the words in given sentence. Example://///////////////////////////////////////////////
  632.  
  633.  
  634.             // output : Delphi not and PHP, not C++ not is C#!
  635.             string text = "C# is not C++, not PHP and not Delphi!";
  636.  
  637.             char sign = text[text.Length - 1];
  638.  
  639.             text = text.Remove(text.Length - 1, 1);
  640.  
  641.             string[] words = text.Split(new[] { ' ',',' }, StringSplitOptions.RemoveEmptyEntries);
  642.             string hui = "";
  643.             for (int i = 4; i > -1; i--)
  644.             {
  645.                 if (i == 4)
  646.                 {
  647.                     hui += " " + words[i] + " ";
  648.                 }
  649.                 else if (i == 0)
  650.                 {
  651.                     hui += words[i];
  652.                 }
  653.                 else
  654.                 {
  655.                     hui += words[i] + " ";
  656.                 }
  657.             }
  658.            
  659.             string[] wordss = text.Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
  660.             Array.Reverse(words);
  661.             string huii = "";
  662.             for (int i = 0; i < 4; i++)
  663.             {
  664.                 if (i == 3)
  665.                 {
  666.                     huii += words[i];
  667.                 }
  668.                 else
  669.                 {
  670.                     huii += words[i] + " ";
  671.                 }
  672.             }
  673.            
  674.  
  675.             Array.Reverse(words);
  676.  
  677.             Console.WriteLine("Result: {0},{1}{2}\n", huii, hui, sign);
  678.  
  679.  
  680. // ОБЯСНЕНИЕ: Тук трябва да използваме Стек и Опашка.
  681.  
  682.  
  683.  
  684. Problem 14. Word dictionary  ////////////////////////////////////////////////////////////////////////////
  685.  
  686.  
  687.     Dictionary<string, string> dict = new Dictionary<string, string>
  688.         {
  689.             {".NET", "platform for applications from Microsoft"},
  690.             {"CLR", "managed execution environment for .NET"},
  691.             {"NAMESPACE", "hierarchical organization of classes"}
  692.         };
  693.  
  694.             Console.WriteLine("Dictionary words: {0}\n", string.Join(", ", dict.Keys));
  695.  
  696.             Console.Write("Enter a word to see its explanation: ");
  697.             string word = Console.ReadLine().ToUpper();
  698.  
  699.             Console.WriteLine(dict.ContainsKey(word) ? string.Format("\n{0} -> {1}\n", word, dict[word])
  700.                               : string.Format("\nDictionary does not contain word \"{0}\".\n", word));
  701.  
  702.  
  703. Problem 15. Replace tags   //////////////////////////////////////////////////////////////////////////////////
  704.  
  705. const string HTML = @"<p>Please visit <a href=""http://academy.telerik.com"">our site</a> to choose a training course. Also visit <a href=""www.devbg.org"">our forum</a> to discuss the courses.</p>";
  706.  
  707.         Console.WriteLine(Regex.Replace(HTML, @"<a href=""(.*?)"">(.*?)</a>", @"[URL=$1]$2[/URL]"));
  708.  
  709.  
  710. Problem 16. Date difference  /////////////////////////////////////////////////////////////////////////////////////
  711.  
  712.  
  713. Console.Write("Enter the first date in the format [dd.MM.yyyy]: ");
  714.         string startDate = Console.ReadLine();
  715.         Console.Write("Enter the second date in the format [dd.MM.yyyy]: ");
  716.         string endDate = Console.ReadLine();
  717.  
  718.         DateTime start = DateTime.ParseExact(startDate, "d.M.yyyy", CultureInfo.InvariantCulture);
  719.         DateTime end = DateTime.ParseExact(endDate, "d.M.yyyy", CultureInfo.InvariantCulture);
  720.  
  721.         Console.WriteLine("Distance between {0} and {1} -> {2} days\n", startDate, endDate, Math.Abs((end - start).TotalDays));
  722.  
  723.  
  724.  
  725.  
  726. Problem 18. Extract e-mails  ///////////////////////////////////////////////////////////////////
  727.  
  728.  
  729. static void Main()
  730.     {
  731.         string text = Console.ReadLine();
  732.  
  733.         string[] emails = text.Split(new[] { " ", ";", ",", ". " }, StringSplitOptions.RemoveEmptyEntries);
  734.         string[] validEmails = Array.FindAll(emails, IsValidEmail);
  735.  
  736.         PrintEmails(validEmails);
  737.     }
  738.  
  739.     static bool IsValidEmail(string email)
  740.     {
  741.         const string pattern = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
  742.                                @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
  743.                                @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
  744.  
  745.         return new Regex(pattern).IsMatch(email);
  746.     }
  747.  
  748.     static void PrintEmails(string[] validEmails)
  749.     {
  750.         Console.WriteLine("Extracted e-mail addresses from the sample text: ");
  751.  
  752.         foreach (string email in validEmails)
  753.             Console.WriteLine("- " + email);
  754.  
  755.         Console.WriteLine();
  756.     }
  757.  
  758.  
  759.  
  760.  
  761.  
  762. Problem 20. Palindromes  //////////////////////////////////////////////////////////////////////////////////////////
  763.  
  764.  
  765. string text = Console.ReadLine();
  766.  
  767.         MatchCollection words = Regex.Matches(text, @"\b\w+\b");
  768.  
  769.         Console.WriteLine("Extracted palindromes from the sample text: ");
  770.  
  771.         foreach (var word in words)
  772.         {
  773.             if (IsPalindrome(word.ToString()))
  774.             {
  775.                 Console.WriteLine("- " + word);
  776.             }
  777.         }
  778.  
  779.         Console.WriteLine();
  780.     }
  781.  
  782.     static bool IsPalindrome(string word)
  783.     {
  784.         return word.ToCharArray().SequenceEqual(word.ToCharArray().Reverse());
  785.     }
  786.  
  787.  
  788.  
  789. /////// moe 2 reshenie /////////////////////////////////
  790.  
  791.  
  792.  
  793.  string kurr = "kuk1ku";
  794.          char[] kur = kurr.ToCharArray();
  795.  
  796.            
  797.  
  798.          Console.WriteLine(IsPalindrome(kur));
  799.         }
  800.  
  801.         static bool IsPalindrome(char[] kur)
  802.         {
  803.  
  804.         bool isSymmetric = true;
  805.         for (int i = 0; i < kur.Length / 2; i++)// na purvoto zavurtane na cikula size = 5 i za tova 5 - 0 - 1 = 4 index koito mi e 1 v slu4aq
  806.         {                                         // pri vtoroto zavurtane mi vzima 1 i 3 element i taka natatuk
  807.             if (kur[i] != kur[kur.Length - i - 1])
  808.             {
  809.                 isSymmetric = false;
  810.                 break;
  811.             }
  812.         }
  813.         return isSymmetric;
  814.         }
  815.  
  816.  
  817.  
  818. Problem 21. Letters count  ///////////////////////////////////////////////////////////////////////////////////////////
  819.  
  820. Console.Write("Enter a string: ");
  821.         char[] letters = Console.ReadLine().ToCharArray();
  822.  
  823.         Dictionary<char, int> dict = new Dictionary<char, int>();
  824.  
  825.         foreach (char t in letters)
  826.         {
  827.             if (!dict.ContainsKey(t))
  828.             {
  829.                 dict.Add(t, 1);
  830.             }
  831.             else
  832.             {
  833.                 dict[t]++;
  834.             }
  835.         }
  836.  
  837.         Console.WriteLine("\nLetter occurence table:\n{0}\n",
  838.             string.Join("\n", dict.Select(x => string.Format(@"'{0}' -> {1} time(s)", x.Key, x.Value)).ToArray()));
  839.     }
  840.  
  841.  
  842.  
  843. Problem 22. Words count  ////////////////////////////////////////////////////////////////////////////
  844.  
  845.  
  846. Console.Write("Enter a string: ");
  847.         string str = Console.ReadLine();
  848.  
  849.         MatchCollection words = Regex.Matches(str, @"\b\w+\b");
  850.         Dictionary<string, int> dict = new Dictionary<string, int>();
  851.  
  852.         foreach (var word in words)
  853.         {
  854.             if (!dict.ContainsKey(word.ToString()))
  855.             {
  856.                 dict.Add(word.ToString(), 1);
  857.             }
  858.             else
  859.             {
  860.                 dict[word.ToString()]++;
  861.             }
  862.         }
  863.  
  864.         Console.WriteLine("\nWord occurence table:\n{0}\n",
  865.             string.Join("\n", dict.Select(x => string.Format(@"'{0}' -> {1} time(s)", x.Key, x.Value)).ToArray()));
  866.     }
  867.  
  868.  
  869. Problem 23. Series of letters   ////////////////////////////////////////////////////////////////////////////////
  870.  
  871.  
  872.                 string sequence = Console.ReadLine();
  873.  
  874.         Console.WriteLine("Result -> {0}\n", ReplaceSequenceWithOneElement(sequence));
  875.     }
  876.  
  877.     static string ReplaceSequenceWithOneElement(string str)
  878.     {
  879.         string result = str[0].ToString();
  880.         for (int i = 1; i < str.Length; i++)
  881.         {
  882.             if (str[i] != result[result.Length - 1])
  883.             {
  884.                 result += str[i];
  885.             }
  886.         }
  887.  
  888.         return result;
  889.     }
  890.  
  891.  
  892.  
  893. Problem 24. Order words  ////////////////////////////////////////////////////////////////////////////////////////
  894.  
  895.  
  896.      Console.Write("Enter a few words (separated by spaces): ");
  897.             string[] words = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  898.  
  899.             Array.Sort(words);
  900.  
  901.             for (int i = 0; i < words.Length; i++) // moje i s for cikul
  902.             {
  903.                 Console.WriteLine(words[i]);
  904.             }
  905.  
  906.             Console.WriteLine("\nWords sorted in alphabetical order:\n{0}\n",
  907.                 string.Join("\n", words.Select(x => string.Format("- {0}", x))));
  908.  
  909.  
  910.  
  911. Problem 25. Extract text from HTML  ////////////////////////////////////////////////////////////////////////////
  912.  
  913.  
  914. const string htmlDoc = @"<html><head><title>News</title></head><body><p><a href=""http://academy.telerik.com"">Telerik Academy</a>aims to provide free real-world practical training for young people who want to turn into skillful .NET software engineers.</p></body></html>";
  915.  
  916.         foreach (Match item in Regex.Matches(htmlDoc, "(?<=^|>)[^><]+?(?=<|$)"))
  917.         {
  918.             Console.WriteLine(item);
  919.         }
  920.  
  921.         Console.WriteLine();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement