예제 #1
1
        public static string[] Split(string str, char[] separators, int maxComponents, StringSplitOptions options)
        {
            ContractUtils.RequiresNotNull(str, "str");
            #if SILVERLIGHT || WP75
            if (separators == null) return SplitOnWhiteSpace(str, maxComponents, options);

            bool keep_empty = (options & StringSplitOptions.RemoveEmptyEntries) != StringSplitOptions.RemoveEmptyEntries;

            List<string> result = new List<string>(maxComponents == Int32.MaxValue ? 1 : maxComponents + 1);

            int i = 0;
            int next;
            while (maxComponents > 1 && i < str.Length && (next = str.IndexOfAny(separators, i)) != -1) {

                if (next > i || keep_empty) {
                    result.Add(str.Substring(i, next - i));
                    maxComponents--;
                }

                i = next + 1;
            }

            if (i < str.Length || keep_empty) {
                result.Add(str.Substring(i));
            }

            return result.ToArray();
            #else
            return str.Split(separators, maxComponents, options);
            #endif
        }
예제 #2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StringParser"/> class.
 /// </summary>
 /// <param name="value">The value.</param>
 /// <param name="separator">The separator.</param>
 /// <param name="splitOptions">The split options.</param>
 public StringParser(string value, string separator, StringSplitOptions splitOptions)
 {
     if (!string.IsNullOrWhiteSpace(value) && !string.IsNullOrEmpty(separator))
     {
         _tokens = value.Split(new string[] { separator }, splitOptions);
     }
 }
예제 #3
0
        public static IEnumerable<KeyValuePair<string, string>> SplitWithSeparator(this string str, IEnumerable<string> separator,
			StringComparison comparisonType = StringComparison.CurrentCulture, StringSplitOptions options = StringSplitOptions.None)
        {
            IEnumerable<KeyValuePair<int, string>> indexes = new Dictionary<int, string>();
            indexes = separator.Aggregate(indexes, (current, s) => current.Union(str.IndexOfAll(s, comparisonType).ToDictionaryValue(i => str.Substring(i, s.Length))));
            int lastIndex = 0;
            var list = new List<KeyValuePair<string, string>>();
            foreach (KeyValuePair<int, string> kvp in indexes.OrderBy(a => a.Key))
            {
                string substring = str.Substring(lastIndex, kvp.Key - lastIndex);
                list.Add(new KeyValuePair<string, string>(substring, kvp.Value));
                lastIndex += substring.Length + kvp.Value.Length;
            }
            list.Add(new KeyValuePair<string, string>(str.Substring(lastIndex), null));
            return list.Where(a =>
            {
                switch (options)
                {
                    case StringSplitOptions.None:
                        return true;
                    case StringSplitOptions.RemoveEmptyEntries:
                        return a.Key != "";
                    default:
                        throw new NotSupportedException("unrecognized StringSplitOptions");
                }
            });
        }
        /// <summary>
        /// Builds a polyline from a string. Optional : keep a subpart of the complete polyline.
        /// </summary>
        /// <param name="line">The input string, under the format [[x_1,y_1],...,[x_n,y_n]].</param>
        /// <param name="partToKeep">The percentage of the first part of the string to keep.</param>
        public Polyline(string line, double partToKeep = 1.1f)
        {
            StringSplitOptions sso = new StringSplitOptions();
            string[] arr = line.Split(new string[] { "[[" }, sso);
            string pl = arr[1];
            pl = pl.Replace("[", "");
            pl = pl.Replace("]", "");
            pl = pl.Replace("\"", "");
            List<string> elts = pl.Split(',').ToList();

            if (partToKeep < 1f)
            {
                int finalSize = (int)Math.Floor(elts.Count * partToKeep / 2 + 1) * 2;
                List<string> elts2 = new List<string>();
                for (int i = 0; i < finalSize; i++)
                    elts2.Add(elts[i]);
                elts = elts2;
            }

            _polylineX = new double[elts.Count / 2];
            _polylineY = new double[elts.Count / 2];

            for (int i = 0; i < _polylineX.Length; i++)
            {
                _polylineX[i] = Convert.ToDouble(elts[i * 2], CultureInfo.GetCultureInfo("en-US"));
                _polylineY[i] = Convert.ToDouble(elts[i * 2 + 1], CultureInfo.GetCultureInfo("en-US"));
            }
        }
예제 #5
0
 public static string[] Split(string str, string[] delimeters, StringSplitOptions options = StringSplitOptions.None)
 {
     StringTokenizer.options = options;
     StringTokenizer.delimeters = delimeters;
     StringTokenizer.str = str;
     List<string> list = new List<string>();
     string cur = "";
     for (int i = 0; i <= str.Length; i++)
     {
         int d = getDelimeter(i);
         if (d == -1)
         {
             if (i < str.Length)
                 cur += str[i];
             else
             {
                 AddToList(list, cur);
                 cur = "";
             }
         }
         else
         {
             AddToList(list, cur);
             cur = "";
             AddToList(list, delimeters[d]);
             i += delimeters[d].Length - 1;
         }
     }
     return list.ToArray();
 }
예제 #6
0
 public static string[] Split(string words, StringSplitOptions splitOptions, bool splitOnCaseDifference)
 {
     if (string.IsNullOrEmpty(words))
     {
         return new string[] { words };
     }
     string[] initial = words.Split(_separators, splitOptions);
     List<string> final = new List<string>();
     int finalIndex = 0;
     for (int i = 0; i < initial.Length; i++)
     {
         StringBuilder sb = new StringBuilder();
         string w = initial[i];
         bool isUpper = char.IsUpper(w[0]);
         sb.Append(w[0]);
         for (int c = 1; c < w.Length; c++)
         {
             if (splitOnCaseDifference && char.IsUpper(w[c]))
             {
                 final.Insert(finalIndex++, sb.ToString());
                 sb.Clear();
             }
             sb.Append(w[c]);
         }
         if (sb.Length > 0)
         {
             final.Insert(finalIndex++, sb.ToString());
             sb.Clear();
         }
     }
     return final.ToArray();
 }
예제 #7
0
        public static string[] Split(string str, string separator, int maxComponents, StringSplitOptions options) {
            ContractUtils.RequiresNotNull(str, "str");
#if SILVERLIGHT || WP75
            if (string.IsNullOrEmpty(separator)) throw new ArgumentNullException("separator");

            bool keep_empty = (options & StringSplitOptions.RemoveEmptyEntries) != StringSplitOptions.RemoveEmptyEntries;

            List<string> result = new List<string>(maxComponents == Int32.MaxValue ? 1 : maxComponents + 1);

            int i = 0;
            int next;
            while (maxComponents > 1 && i < str.Length && (next = str.IndexOf(separator, i)) != -1) {

                if (next > i || keep_empty) {
                    result.Add(str.Substring(i, next - i));
                    maxComponents--;
                }

                i = next + separator.Length;
            }

            if (i < str.Length || keep_empty) {
                result.Add(str.Substring(i));
            }

            return result.ToArray();
#else
            return str.Split(new string[] { separator }, maxComponents, options);
#endif
        }
예제 #8
0
        public static string[] SplitOnWhiteSpace(string str, int maxComponents, StringSplitOptions options) {
            ContractUtils.RequiresNotNull(str, "str");

            bool keep_empty = (options & StringSplitOptions.RemoveEmptyEntries) != StringSplitOptions.RemoveEmptyEntries;

            List<string> result = new List<string>(maxComponents == Int32.MaxValue ? 1 : maxComponents + 1);

            int i = 0;
            int next;
            while (maxComponents > 1 && i < str.Length && (next = IndexOfWhiteSpace(str, i)) != -1) {

                if (next > i || keep_empty) {
                    result.Add(str.Substring(i, next - i));
                    maxComponents--;
                }

                i = next + 1;
            }

            if (i < str.Length || keep_empty) {
                result.Add(str.Substring(i));
            }

            return result.ToArray();
        }
예제 #9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StringParser"/> class.
 /// </summary>
 /// <param name="value">The value.</param>
 /// <param name="separator">The separator.</param>
 /// <param name="splitOptions">The split options.</param>
 public StringParser(string value, char separator, StringSplitOptions splitOptions)
 {
     if (!string.IsNullOrWhiteSpace(value))
     {
         _tokens = value.Split(new char[] { separator }, splitOptions);
     }
 }
예제 #10
0
        public static string[] ToArray(this string input, StringSplitOptions option, params char[] delimiter)
        {
            if (input == null)
            {
                return null;
            }

            return input.Split(delimiter, option);
        }
예제 #11
0
        /// <summary>
        ///     Returns a string array that contains the substrings in this string that are
        ///     delimited by elements of a specified string array. A parameter specifies
        ///     whether to return empty array elements.
        /// </summary>
        /// <exception cref="ArgumentNullException">The string can not be null.</exception>
        /// <exception cref="ArgumentNullException">The separator can not be null.</exception>
        /// <param name="value">The string to split.</param>
        /// <param name="separators">
        ///     An array of strings that delimit the substrings in this string, an empty
        ///     array that contains no delimiters, or null.
        /// </param>
        /// <param name="stringSplitOption">
        ///     <see cref="System.StringSplitOptions.RemoveEmptyEntries" /> to omit empty array elements
        ///     from the array returned; or System.StringSplitOptions.None to include empty
        ///     array elements in the array returned.
        /// </param>
        /// <returns>
        ///     Returns an array whose elements contain the substrings in this string that are delimited
        ///     by one or more strings in separator.
        /// </returns>
        public static String[] Split( this String value,
                                      StringSplitOptions stringSplitOption,
                                      params String[] separators )
        {
            value.ThrowIfNull( nameof( value ) );
            separators.ThrowIfNull( nameof( separators ) );

            return value.Split( separators, stringSplitOption );
        }
예제 #12
0
        public static string[] split_safe(this string s, char[] separator, StringSplitOptions stringSplitOptions)
        {
            if (s == null)
            {
                return new string[0];
            }

            return s.Split(separator, stringSplitOptions);
        }
 private static IEnumerable<string> GetAllSettingsAsString(
     IEnumerable<string> returns,
     char separator = ',',
     StringSplitOptions options = StringSplitOptions.RemoveEmptyEntries)
 {
     return CreateSubjectUnderTest(
         string.Join(separator.ToString(), returns))
         .GetAllSettingsAsString(Key, separator, options);
 }
예제 #14
0
        /// <summary>
        ///     Splits the given string at each line break (<see cref="Environment.NewLine" />).
        /// </summary>
        /// <example>value can not be null.</example>
        /// <param name="value">The string to split.</param>
        /// <param name="stringSplitOptions">
        ///     <see cref="System.StringSplitOptions.RemoveEmptyEntries" /> to omit empty array elements
        ///     from the array returned; or System.StringSplitOptions.None to include empty
        ///     array elements in the array returned.
        /// </param>
        /// <returns>
        ///     Returns an array whose elements contain the substrings in this string that are delimited by
        ///     <see cref="Environment.NewLine" />.
        /// </returns>
        public static String[] SplitLines( this String value, StringSplitOptions stringSplitOptions )
        {
            value.ThrowIfNull( nameof( value ) );

            return value.Split( new[]
            {
                Environment.NewLine
            },
                                stringSplitOptions );
        }
예제 #15
0
 /// <summary>
 /// Splits a given strings into elements by a given sperator.
 /// </summary>
 /// <param name="IEnumerator">An enumerator of strings.</param>
 /// <param name="IgnoreLines">A regular expression indicating which input strings should be ignored. Default: All lines starting with a '#'.</param>
 /// <param name="Seperators">An array of string used to split the input strings.</param>
 /// <param name="StringSplitOptions">Split options, e.g. remove empty entries.</param>
 /// <param name="ExpectedNumberOfColumns">If the CSV file had a schema, a specific number of columns can be expected. If instead it is a list of values no such value can be expected.</param>
 /// <param name="FailOnWrongNumberOfColumns">What to do when the current and expected number of columns do not match.</param>
 /// <param name="TrimColumns">Remove leading and trailing whitespaces.</param>
 /// <returns>An enumeration of string arrays.</returns>
 public static IEnumerable<String[]> CSVPipe(this IEnumerator<String> IEnumerator,
                                                  Regex               IgnoreLines                = null,
                                                  String[]            Seperators                 = null,
                                                  StringSplitOptions  StringSplitOptions         = StringSplitOptions.None,
                                                  UInt16?             ExpectedNumberOfColumns    = null,
                                                  Boolean             FailOnWrongNumberOfColumns = false,
                                                  Boolean             TrimColumns                = true)
 {
     return new CSVReaderPipe(IgnoreLines, Seperators, StringSplitOptions, ExpectedNumberOfColumns, FailOnWrongNumberOfColumns, TrimColumns, null, IEnumerator);
 }
예제 #16
0
        public static int[] stringToIntArray(string input, char[] separator, StringSplitOptions option)
        {
            string[] tempArray = input.Trim().Split(separator, option);
            int[] result = new int[tempArray.Length];
            for (int i = 0; i < tempArray.Length; i++)
            {
                result[i] = int.Parse(tempArray[i].Trim());
            }

            return result;
        }
예제 #17
0
 public void TestSplit(string words, StringSplitOptions splitOptions, bool splitOnCaseDifference, string[] expected)
 {
     var result = BaseRenameRule.Split(words, splitOptions, splitOnCaseDifference);
     Assert.AreEqual(expected.Length, result.Length);
     Console.WriteLine(result.Length);
     Console.WriteLine(result[0]);
     Console.WriteLine(result[1]);
     for (int i = 0; i < expected.Length; i++)
     {
         Assert.AreEqual(expected[i],result[i]);
     }
 }
        public static string[] Split(this string source, char[] spliter, int count, StringSplitOptions options)
        {
            var parts = source.Split(spliter, options);

            if (parts.Length <= count)
                return parts.ToArray();

            var partList = parts.Take(count - 1).ToList();
            partList.Add(string.Join(spliter[0].ToString(), parts, count - 1, parts.Length - count + 1));
            parts = partList.ToArray();
            return parts;
        }
        static void AssertTextEqual(string expected, string actual, string message, StringSplitOptions options = StringSplitOptions.RemoveEmptyEntries)
        {
            var eLines = expected.Split(new char[] { '\n', '\r' }, options);
            var aLines = actual.Split(new char[] { '\n', '\r' }, options);

            for (var i = 0; i < Math.Min(eLines.Length, aLines.Length); i++)
            {
                Assert.AreEqual(eLines[i], aLines[i], message);
            }

            Assert.AreEqual(eLines.Length, aLines.Length, message);
        }
예제 #20
0
        /// <summary>
        /// 将当前字符串对象按照指定的分隔符转换为字符串数组
        /// </summary>
        /// <param name="str">当前要转换的字符串对象</param>
        /// <param name="split">指定的分隔字符列表</param>
        /// <param name="opt">指定转换后的数组是否要包含为空的项,默认为不包含</param>
        /// <returns>如果当前字符串为空,返回NULL,否则返回转换后的数组对象</returns>
        public static string[] ToArray(this string str, string split = ",", StringSplitOptions opt = StringSplitOptions.RemoveEmptyEntries)
        {
            if (General.IsNullable(str))
                return null;

            string[] strArray = null;
            if (General.IsNullable(split) || str.IndexOf(split) == -1)
                strArray = new string[] { str };
            else
                strArray = str.Split(split.ToCharArray(), opt);

            return strArray;
        }
예제 #21
0
        /// <summary>
        ///     Returns a string array that contains the substrings in this string that are
        ///     delimited by the given separator. A parameter specifies
        ///     whether to return empty array elements.
        /// </summary>
        /// <exception cref="ArgumentNullException">The string can not be null.</exception>
        /// <exception cref="ArgumentNullException">The separator can not be null.</exception>
        /// <param name="value">The string to split.</param>
        /// <param name="separator">A string that delimit the substrings in this string.</param>
        /// <param name="stringSplitOption">
        ///     <see cref="System.StringSplitOptions.RemoveEmptyEntries" /> to omit empty array elements
        ///     from the array returned; or System.StringSplitOptions.None to include empty
        ///     array elements in the array returned.
        /// </param>
        /// <returns>
        ///     Returns an array whose elements contain the substrings in this string that are delimited by the separator.
        /// </returns>
        public static String[] Split( this String value,
                                      String separator,
                                      StringSplitOptions stringSplitOption = StringSplitOptions.None )
        {
            value.ThrowIfNull( nameof( value ) );
            separator.ThrowIfNull( nameof( separator ) );

            return value.Split( new[]
            {
                separator
            },
                                stringSplitOption );
        }
예제 #22
0
		/// <summary>
		/// Splits a <c>string</c> using a Unicode character, unless that character is contained between matching <paramref name="start"/> and <paramref name="end"/> Unicode characters.
		/// </summary>
		/// <param name="st">The <c>string</c> to split.</param>
		/// <param name="separator">Unicode <c>char</c> that delimits the substrings in this instance.</param>
		/// <param name="start">The starting (left) container character. EX: '('.</param>
		/// <param name="end">The ending (right) container character. EX: ')'.</param>
		/// <returns>Array of <c>string</c> objects that are the resulting substrings.</returns>
		public static string[] SplitUnlessBetweenDelimiters(this string st, char separator, char start, char end, StringSplitOptions options = StringSplitOptions.None) {
			List<string> results = new List<string>();
			int containerLevel = 0;
			StringBuilder current = new StringBuilder();
			foreach (char c in st) {
				if (c == start) {
					++containerLevel;
					if (containerLevel == 1) {
						continue;
					}
				}

				if (c == end) {
					--containerLevel;
					if (containerLevel == 0) {
						continue;
					}
				}

				if (containerLevel == 0) {
					if (c == separator) {
						switch (options) {
							case StringSplitOptions.RemoveEmptyEntries: {
								if (current.Length > 0) {
									results.Add(current.ToString());
								}
								current.Length = 0;
								break;
							}
							case StringSplitOptions.None: {
								results.Add(current.ToString());
								current.Length = 0;
								break;
							}
						}
					} else {
						current.Append(c);
					}
				} else {
					current.Append(c);
				}
			}

			if (current.Length > 0) {
				results.Add(current.ToString());
			}

			return results.ToArray<string>();
		}
예제 #23
0
        public static String[] Split(string toSeperate, char separator, int count, StringSplitOptions options)
        {
            if (count < 0)
                throw new ArgumentOutOfRangeException("count", "Count cannot be less than zero.");
            if ((options != StringSplitOptions.None) && (options != StringSplitOptions.RemoveEmptyEntries))
                throw new ArgumentException("Illegal enum value: " + options + ".");

            if (toSeperate.Length == 0 && (options & StringSplitOptions.RemoveEmptyEntries) != 0)
                return new string[0];

            if (count == 1)
            {
                return count == 0 ? new string[0] : new String[1] { toSeperate};
            }
            return SplitByCharacters(toSeperate, separator, count, options != 0);
        }    
 public static string[][] LoadDelimitedFile( string fileName, char[] separators, StringSplitOptions splitOptions = StringSplitOptions.None )
 {
     if( !System.IO.File.Exists( fileName ) )
         throw new ArgumentException( "Cannot find delimited file: " + fileName );
     List<string[]> result = new List<string[]>( );
     string line = string.Empty;
     using( StreamReader sr = new StreamReader( fileName ) )
     {
         while( true )
         {
             line = sr.ReadLine( );
             if( line == string.Empty || line == null )
                 break;
             result.Add( line.Split( separators, splitOptions ) );
         }
     }
     return result.ToArray( );
 }
예제 #25
0
		/// <summary>
		/// Splits a <c>string</c> using a Unicode character, unless that character is between two instances of a container.
		/// </summary>
		/// <param name="st">The <c>string</c> to split.</param>
		/// <param name="separator">Unicode <c>char</c> that delimits the substrings in this instance.</param>
		/// <param name="container">Container <c>char</c>. Any <paramref name="separator"/> characters that occur between two instances of this character will be ignored.</param>
		/// <returns>Array of <c>string</c> objects that are the resulting substrings.</returns>
		public static string[] SplitUnlessInContainer(this string st, char separator, char container, StringSplitOptions options = StringSplitOptions.None) {
			if (st.IndexOf(separator) < 0) { return new string[] { st }; }
			if (st.IndexOf(container) < 0) { return st.Split(new char[] { separator }, options); }

			List<string> results = new List<string>();
			bool inContainer = false;
			StringBuilder current = new StringBuilder();
			foreach (char c in st) {
				if (c == container) {
					inContainer = !inContainer;
					continue;
				}

				if (!inContainer) {
					if (c == separator) {
						switch (options) {
							case StringSplitOptions.RemoveEmptyEntries: {
								if (current.Length > 0) {
									results.Add(current.ToString());
								}
								current.Length = 0;
								break;
							}
							case StringSplitOptions.None: {
								results.Add(current.ToString());
								current.Length = 0;
								break;
							}
						}
					} else {
						current.Append(c);
					}
				} else {
					current.Append(c);
				}
			}

			if (current.Length > 0) {
				results.Add(current.ToString());
			}

			return results.ToArray<string>();
		}
예제 #26
0
            private string[] FillStreamAndRetrieveWithAStreamReader(int numberOfLines, StringSplitOptions stringSplitOptions, bool resetStream = true)
            {
                _streamFiller = new StreamFiller(numberOfLines);
                using (var stream = new MemoryStream())
                {
                    using (var writer = new StreamWriter(stream))
                    {
                        _streamFiller.Fill(writer);

                        if (resetStream)
                        {
                            stream.Position = 0;
                        }
                        using (var reader = new StreamReader(stream))
                        {
                            return reader.ReadToEnd().Split(new[] { "\r\n" }, stringSplitOptions);
                        }
                    }
                }
            }
 public static List <string> SplitString(string strStringToSplit, char[] chSplitBy, StringSplitOptions splitOptions = StringSplitOptions.None)
 {
     return(strStringToSplit.Split(chSplitBy, splitOptions).ToList());
 }
예제 #28
0
        public static string[] Split(this string s, string[] separator, int count, StringSplitOptions options)
        {
            if (s == null)
            {
                throw new ArgumentNullException(nameof(s));
            }

            if (count < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(count),
                                                      "The counting cannot be negative");
            }

            if (options < StringSplitOptions.None || options > StringSplitOptions.RemoveEmptyEntries)
            {
                throw new ArgumentException("Illegal value for string split options");
            }

            bool omitEmptyEntries = (options == StringSplitOptions.RemoveEmptyEntries);
            bool singleSeparator  = (separator != null) ? separator.Length == 1 : false;

            if (!singleSeparator && (separator == null || separator.Length == 0))
            {
                return(Split(s, (char[])null, count, options));
            }

            if (count == 0 || (omitEmptyEntries && s.Length == 0))
            {
                return(new string[0]);
            }

            if (count == 1 || (singleSeparator && separator[0].Length == 0))
            {
                return new string[] { s }
            }
            ;

            int[] sepList = new int[s.Length];
            int[] lengthList;
            int   defaultLength;
            int   numReplaces;

            if (singleSeparator)
            {
                lengthList = null;

                defaultLength = separator[0].Length;
                numReplaces   = MakeSeparatorList(s, separator[0], sepList);
            }
            else
            {
                lengthList    = new int[s.Length];
                defaultLength = 0;
                numReplaces   = MakeSeparatorList(s, separator, sepList, lengthList);
            }

            // Handle the special case of no replaces.
            if (numReplaces == 0)
            {
                return new string[] { s }
            }
            ;

            if (omitEmptyEntries)
            {
                return(SplitOmitEmptyEntries(s, sepList, lengthList, defaultLength, numReplaces, count));
            }
            else
            {
                return(SplitKeepEmptyEntries(s, sepList, lengthList, defaultLength, numReplaces, count));
            }
        }
 public static string[] Split(this string obj, StringSplitOptions splitOptions, params string[] array)
 {
     return obj.Split(array, splitOptions);
 }
 public static string[] Split(this string source, string split, int count = -1, StringSplitOptions options = StringSplitOptions.None)
 {
     if (count != -1)
     {
         return(source.Split(new string[] { split }, count, options));
     }
     return(source.Split(new string[] { split }, options));
 }
예제 #31
0
 public static string[] Split(this string s, string[] separator, StringSplitOptions options)
 => Split(s, separator, int.MaxValue, options);
예제 #32
0
 /// <summary>
 /// Splits the contents of <paramref name="span"/> on whitespace characters.
 /// </summary>
 /// <param name="span">The chars to split.</param>
 /// <param name="stringSplitOptions">The split options.</param>
 public static SpanSplitEnumerator <char> Split(this ReadOnlySpan <char> span, StringSplitOptions stringSplitOptions = StringSplitOptions.None)
 => Split(span, ' ', stringSplitOptions);
예제 #33
0
 /// <summary>
 /// 基于字符串将字符串拆分为多个子字符串。可以指定子字符串是否包含空数组元素。
 /// </summary>
 /// <param name="value">字符串</param>
 /// <param name="separator">分隔此字符串中子字符串的字符串数组、不包含分隔符的空数组或 null。</param>
 /// <param name="options">要省略返回的数组中的空数组元素,则为 StringSplitOptions.RemoveEmptyEntries;要包含返回的数组中的空数组元素,则为 StringSplitOptions.None。</param>
 /// <returns>一个数组,其元素包含此字符串中的子字符串,这些子字符串由 separator 中的一个或多个字符串分隔。 有关详细信息,请参阅“备注”部分。</returns>
 public static string[] Split(this string value, string separator, StringSplitOptions options = StringSplitOptions.None)
 {
     return(value.Split(new string[] { separator }, options));
 }
예제 #34
0
        private static RubyArray/*!*/ InternalSplit(MutableString/*!*/ self, MutableString separator, StringSplitOptions options, int maxComponents) {
            if (separator == null || separator.Length == 1 && separator.GetChar(0) == ' ') {
                return WhitespaceSplit(self, maxComponents);
            }

            if (maxComponents <= 0) {
                maxComponents = Int32.MaxValue;
            }

            RubyArray result = new RubyArray(maxComponents == Int32.MaxValue ? 1 : maxComponents + 1);
            bool keepEmpty = (options & StringSplitOptions.RemoveEmptyEntries) != StringSplitOptions.RemoveEmptyEntries;

            int selfLength = self.Length;
            int i = 0;
            int next;
            while (maxComponents > 1 && i < selfLength && (next = IndexOf(self, separator, i)) != -1) {

                if (next > i || keepEmpty) {
                    result.Add(self.CreateInstance().Append(self, i, next - i).TaintBy(self));
                    maxComponents--;
                }

                i = next + separator.Length;
            }

            if (i < selfLength || keepEmpty) {
                result.Add(self.CreateInstance().Append(self, i, selfLength - i).TaintBy(self));
            }

            return result;
        }
예제 #35
0
 /// <summary>
 /// <para>改行コード ("\r\n", "\r", "\n") に基づいて文字列を部分文字列に分割します。
 /// 部分文字列が空の配列の要素を含めるかどうかを指定することができます。</para>
 /// <para>文字列が <see langword="null"/> の場合は空の配列を返します。</para>
 /// </summary>
 /// <param name="str">文字列。</param>
 /// <param name="options">返される配列から空の配列要素を省略する場合は <see cref="StringSplitOptions.RemoveEmptyEntries"/>。返される配列に空の配列要素も含める場合は <see cref="StringSplitOptions.None"/>。</param>
 /// <returns>文字列を改行コード ("\r\n", "\r", "\n") で区切ることによって取り出された部分文字列を格納する配列。</returns>
 public static string[] ToLines(this string?str, StringSplitOptions options = StringSplitOptions.None)
 {
     return((str == null) ? Array.Empty <string>() : (str.Split(newLineCodes, options) ?? Array.Empty <string>()));
 }
 /// <summary>
 /// Provides an additional overload for string.split
 /// </summary>
 /// <param name="val">The val.</param>
 /// <param name="separator">The separator.</param>
 /// <param name="options">The options.</param>
 /// <returns>System.String[][].</returns>
 private static string[] Split(string val, char separator, StringSplitOptions options)
 {
     return(val.Split(new[] { separator }, options));
 }
예제 #37
0
        public static string[] ConvertCsvToStringArray(string str, char separator = ',', StringSplitOptions options = StringSplitOptions.RemoveEmptyEntries)
        {
            if (str == null)
            {
                return(null);
            }

            var array = str.Split(new[] { separator }, options);

            return(array);
        }
        public static string[] SplitAndKeep(this string source, char[] delimiters, StringSplitOptions options)
        {
            var pattern = @"(?<=[" + new string(delimiters) + @"])";

            return(System.Text.RegularExpressions.Regex.Split(source, pattern /*,options*/));
        }
예제 #39
0
 public string[] Split(string s, char[] arr, StringSplitOptions options)
 => s.Split(arr, options);
 // 根据符号ch对串str进行拆分
 public static string[] split(string str, char ch, StringSplitOptions op = StringSplitOptions.None)
 {
     char[]   sp  = { ch };
     string[] arr = str.Split(sp, op);
     return(arr);
 }
예제 #41
0
            internal SpanSplitSequenceEnumerator(ReadOnlySpan <T> span, ReadOnlySpan <T> separator, StringSplitOptions stringSplitOptions)
            {
                Sequence     = span;
                SplitOptions = stringSplitOptions;

                var separatorIndices = new StackList <int>(2);

                SeparatorLength = separator.Length;

                //https://github.com/dotnet/runtime/blob/master/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs#L1579
                for (int i = 0; i < span.Length; ++i)
                {
                    if (span[i].Equals(separator[0]) && SeparatorLength <= span.Length - i)
                    {
                        if (SeparatorLength == 1 || span.Slice(i, SeparatorLength).SequenceEqual(separator))
                        {
                            separatorIndices.Append(i);
                            i += SeparatorLength - 1;
                        }
                    }
                }
                SeparatorIndices = separatorIndices;

                Index          = 0;
                SeparatorIndex = 0;
                StartIndex     = 0;
                Offset         = 0;
            }
예제 #42
0
 public static string[] Split(this string input, string splitString, StringSplitOptions options)
 {
     return(input.Split(new string[] { splitString }, options));
 }
예제 #43
0
 /// <summary>
 /// Provides an additional overload for string.split
 /// </summary>
 /// <param name="val">The val.</param>
 /// <param name="separators">The separators.</param>
 /// <param name="options">The options.</param>
 /// <returns>System.String[][].</returns>
 private static string[] Split(string val, char[] separators, StringSplitOptions options)
 {
     return(val.Split(separators, options));
 }
예제 #44
0
        public static void TrySplit(this string value, out string a, out string b, out string c, StringSplitOptions splitOptions, params string[] parameters)
        {
            a = b = c = string.Empty;

            var tokens       = value.Split(parameters, splitOptions);
            var tokensLength = tokens.Length;

            if (tokensLength > 0)
            {
                a = tokens[0];
            }
            if (tokensLength > 1)
            {
                b = tokens[1];
            }
            if (tokensLength > 2)
            {
                c = tokens[2];
            }
        }
예제 #45
0
            internal SpanSplitEnumerator(ReadOnlySpan <T> span, [MaybeNull] T separator, StringSplitOptions stringSplitOptions)
            {
                Sequence     = span;
                SplitOptions = stringSplitOptions;

                var separatorIndices = new StackList <int>(2);

                for (int i = 0; i < span.Length; ++i)
                {
                    if (span[i].Equals(separator))
                    {
                        separatorIndices.Append(i);
                    }
                }
                SeparatorIndices = separatorIndices;

                Index          = 0;
                SeparatorIndex = 0;
                StartIndex     = 0;
                Offset         = 0;
            }
예제 #46
0
 public static string[] SplitOf(this string value, StringSplitOptions splitOptions, params string[] parameters)
 {
     return(value.Split(parameters, splitOptions));
 }
예제 #47
0
 // string.Split has different signatures across .NET Framework/Core, so use an extension so we can use a single signature
 public static string[] Split(this string original, char separator, StringSplitOptions options) => original.Split(separator);
예제 #48
0
 /// <summary>
 /// Uses string.Split method to split given string by <see cref="Environment.NewLine"/>.
 /// </summary>
 public static string[] SplitToLines(this string str, StringSplitOptions options)
 {
     return(str.Split(Environment.NewLine, options));
 }
        // マネージャーのソース更新
        private static void UpdateManagerSource(GENERATE_MODE mode)
        {
            string             src  = File.ReadAllText(managedPath["Scripts/Manager/SceneStateManager.cs"]);
            StringSplitOptions none = StringSplitOptions.None;

            string src_nsp = src.Split(new string[] { "\t{" }, 3, none)[0];
            string src_pre = src.Split(new string[] { "\t{" }, 3, none)[1];
            string src_enm = src.Split(new string[] { "\t{" }, 3, none)[2].Split(new string[] { "\t}" }, 2, none)[0];
            string src_mid = src.Split(new string[] { "\t{" }, 3, none)[2].Split(new string[] { "\t}" }, 2, none)[1].Split(new string[] { "\t{" }, 2, none)[0];
            string src_tbl = src.Split(new string[] { "\t{" }, 3, none)[2].Split(new string[] { "\t}" }, 2, none)[1].Split(new string[] { "\t{" }, 2, none)[1].Split(new string[] { "\t};" }, 2, none)[0];
            string src_pst = src.Split(new string[] { "\t{" }, 3, none)[2].Split(new string[] { "\t}" }, 2, none)[1].Split(new string[] { "\t{" }, 2, none)[1].Split(new string[] { "\t};" }, 2, none)[1];

            // enum行の配列
            List <string> list_enm = new List <string>(src_enm.Trim().Split(new string[] { "\n" }, none));

            if (list_enm.Count == 1)
            {
                list_enm = new List <string>(src_enm.Trim().Split(new string[] { "\r\n" }, none));
            }
            for (int i = 0; i < list_enm.Count; i++)
            {
                list_enm[i] = list_enm[i].Trim();
            }

            if (mode == GENERATE_MODE.ADD)
            {
                foreach (StateInfo state in currentStateInfos)
                {
                    string name = state.className.ToUpper().Replace("STATE", "");

                    string contain = "";
                    foreach (string s in list_enm)
                    {
                        if (s.Contains(name))
                        {
                            contain = s;
                            break;
                        }
                    }

                    if (contain == "")
                    {
                        list_enm.Add(name + ",");
                    }
                }
            }
            else if (mode == GENERATE_MODE.DELETE)
            {
                List <string> tmp_list_enm = new List <string>();
                foreach (StateInfo state in currentStateInfos)
                {
                    string name = state.className.ToUpper().Replace("STATE", "");

                    string contain = "";
                    foreach (string s in list_enm)
                    {
                        if (s.Contains(name))
                        {
                            contain = s;
                            break;
                        }
                    }

                    if (contain != "")
                    {
                        tmp_list_enm.Add(contain);
                    }
                }

                list_enm = new List <string>();
                foreach (string e in tmp_list_enm)
                {
                    list_enm.Add(e);
                }
            }

            // table行の配列
            List <string> list_tbl = new List <string>(src_tbl.Trim().Split(new string[] { "\r\n" }, none));

            if (list_tbl.Count == 1)
            {
                list_tbl = new List <string>(src_tbl.Trim().Split(new string[] { "\n" }, none));
            }
            for (int i = 0; i < list_tbl.Count; i++)
            {
                list_tbl[i] = list_tbl[i].Trim();
            }

            if (mode == GENERATE_MODE.ADD)
            {
                foreach (StateInfo state in currentStateInfos)
                {
                    string name = state.className.ToUpper().Replace("STATE", "");

                    string contain = "";
                    foreach (string s in list_tbl)
                    {
                        if (s.Contains(name))
                        {
                            contain = s;
                            break;
                        }
                    }

                    if (contain == "")
                    {
                        list_tbl.Add("{ SceneState." + name + ", typeof(" + state.className + ") },");
                    }
                }
            }
            else if (mode == GENERATE_MODE.DELETE)
            {
                List <string> tmp_list_tbl = new List <string>();
                foreach (StateInfo state in currentStateInfos)
                {
                    string name = state.className.ToUpper().Replace("STATE", "");

                    string contain = "";
                    foreach (string s in list_tbl)
                    {
                        if (s.Contains(name))
                        {
                            contain = s;
                            break;
                        }
                    }

                    if (contain != "")
                    {
                        tmp_list_tbl.Add(contain);
                    }
                }

                list_tbl = new List <string>();
                foreach (string t in tmp_list_tbl)
                {
                    list_tbl.Add(t);
                }
            }

            // 内容更新
            string src_out = "";

            src_out += src_nsp;
            src_out += "\t{";
            src_out += src_pre;
            src_out += "\t{\n";
            foreach (string e in list_enm)
            {
                src_out += "\t\t\t" + (e.Contains(",") ? e : (e + ",")) + "\n";
            }
            src_out += "\t\t}";
            src_out += src_mid;
            src_out += "\t{\n";
            foreach (string t in list_tbl)
            {
                src_out += "\t\t\t" + (t.Contains(",") ? t : (t + ",")) + "\n";
            }
            src_out += "\t\t};";
            src_out += src_pst;

            // 書き込み
            using (FileStream fs = File.Open(managedPath["Scripts/Manager/SceneStateManager.cs"], FileMode.Create))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.Write("");
                    sw.Write(src_out);
                }
            }
        }
예제 #50
0
 /// <summary>
 ///     Returns a String array containing the substrings in this string that are delimited by elements of a specified
 ///     String array. A parameter specifies whether to return empty array elements.
 /// </summary>
 /// <param name="this">The @this to act on.</param>
 /// <param name="separator">A string that delimit the substrings in this string.</param>
 /// <param name="option">
 ///     (Optional) Specify RemoveEmptyEntries to omit empty array elements from the array returned,
 ///     or None to include empty array elements in the array returned.
 /// </param>
 /// <returns>
 ///     An array whose elements contain the substrings in this string that are delimited by the separator.
 /// </returns>
 public static string[] Split(this string @this, string separator, StringSplitOptions option = StringSplitOptions.None)
 {
     return(@this.Split(new[] { separator }, option));
 }
예제 #51
0
 public static string[] Split2(this string str, string splitStr, StringSplitOptions option)
 {
     return(str.Split(new string[] { splitStr }, option));
 }
예제 #52
0
        public WizardModule()
        {
            Get["/wizard/data"] = x => {
                var timezones   = Bash.Execute("timedatectl list-timezones --no-pager").SplitBash();
                var hosts       = CommandLauncher.Launch("cat-etc-hosts").ToArray();
                var networks    = CommandLauncher.Launch("cat-etc-networks").ToArray();
                var resolv      = CommandLauncher.Launch("cat-etc-resolv").ToArray();
                var nsswitch    = CommandLauncher.Launch("cat-etc-nsswitch").ToArray();
                var hostnamectl = CommandLauncher.Launch("hostnamectl").ToList();
                const StringSplitOptions ssoree = StringSplitOptions.RemoveEmptyEntries;
                var model = new PageWizardModel {
                    Timezones            = timezones,
                    NetworkInterfaceList = NetworkConfiguration.InterfacePhysical,
                    DomainInt            = HostConfiguration.Host.InternalDomain,
                    DomainExt            = HostConfiguration.Host.ExternalDomain,
                    Hosts          = hosts.JoinToString(Environment.NewLine),
                    Networks       = networks.JoinToString(Environment.NewLine),
                    Resolv         = resolv.JoinToString(Environment.NewLine),
                    Nsswitch       = nsswitch.JoinToString(Environment.NewLine),
                    StaticHostname = hostnamectl.First(_ => _.Contains("Static hostname:")).Split(new[] { ":" }, 2, ssoree)[1],
                    Chassis        = hostnamectl.First(_ => _.Contains("Chassis:")).Split(new[] { ":" }, 2, ssoree)[1],
                    Deployment     = hostnamectl.First(_ => _.Contains("Deployment:")).Split(new[] { ":" }, 2, ssoree)[1],
                    Location       = hostnamectl.First(_ => _.Contains("Location:")).Split(new[] { ":" }, 2, ssoree)[1],
                };
                return(JsonConvert.SerializeObject(model));
            };

            Post["/wizard"] = x => {
                ConsoleLogger.Log("[wizard] start basic configuration");
                string password      = Request.Form.Password;
                var    masterManager = new ManageMaster();
                masterManager.ChangePassword(password);
                ConsoleLogger.Log("[wizard] changed master password");
                string hostname   = Request.Form.Hostname;
                string location   = Request.Form.Location;
                string chassis    = Request.Form.Chassis;
                string deployment = Request.Form.Deployment;
                ConsoleLogger.Log($"[wizard] host info:\t{hostname}");
                ConsoleLogger.Log($"[wizard] host info:\t{location}");
                ConsoleLogger.Log($"[wizard] host info:\t{chassis}");
                ConsoleLogger.Log($"[wizard] host info:\t{deployment}");
                HostConfiguration.SetHostInfoName(hostname);
                HostConfiguration.SetHostInfoChassis(chassis);
                HostConfiguration.SetHostInfoDeployment(deployment);
                HostConfiguration.SetHostInfoLocation(location);
                HostConfiguration.ApplyHostInfo();
                string timezone = Request.Form.Timezone;
                HostConfiguration.SetTimezone(timezone);
                HostConfiguration.ApplyTimezone();
                string ntpServer = Request.Form.NtpServer;
                HostConfiguration.SetNtpdate(ntpServer);
                HostConfiguration.ApplyNtpdate();
                string domainInt = Request.Form.DomainInt;
                string domainExt = Request.Form.DomainExt;
                string hosts     = Request.Form.Hosts;
                string networks  = Request.Form.Networks;
                string resolv    = Request.Form.Resolv;
                string nsswitch  = Request.Form.Nsswitch;
                HostConfiguration.SetNsHosts(hosts.Contains("\n")
                    ? hosts.SplitToList("\n").ToArray()
                    : hosts.SplitToList(Environment.NewLine).ToArray());
                HostConfiguration.ApplyNsHosts();
                HostConfiguration.SetNsNetworks(networks.Contains("\n")
                    ? networks.SplitToList("\n").ToArray()
                    : networks.SplitToList(Environment.NewLine).ToArray());
                HostConfiguration.ApplyNsNetworks();
                HostConfiguration.SetNsResolv(resolv.Contains("\n")
                  ? resolv.SplitToList("\n").ToArray()
                  : resolv.SplitToList(Environment.NewLine).ToArray());
                HostConfiguration.ApplyNsResolv();
                HostConfiguration.SetNsSwitch(nsswitch.Contains("\n")
                  ? nsswitch.SplitToList("\n").ToArray()
                  : nsswitch.SplitToList(Environment.NewLine).ToArray());
                HostConfiguration.ApplyNsSwitch();
                HostConfiguration.SetInternalDomain(domainInt);
                HostConfiguration.SetExtenalDomain(domainExt);
                ConsoleLogger.Log("[wizard] name services configured");
                string Interface     = Request.Form.Interface;
                string txqueuelen    = Request.Form.Txqueuelen;
                string mtu           = Request.Form.Mtu;
                string mode          = Request.Form.Mode;
                string staticAddress = Request.Form.StaticAddress;
                string staticRange   = Request.Form.StaticRange;
                var    model         = new NetworkInterfaceConfigurationModel {
                    Interface     = Interface,
                    Mode          = (NetworkInterfaceMode)Enum.Parse(typeof(NetworkInterfaceMode), mode),
                    Status        = NetworkInterfaceStatus.Up,
                    StaticAddress = staticAddress,
                    StaticRange   = staticRange,
                    Txqueuelen    = txqueuelen,
                    Mtu           = mtu,
                    Type          = NetworkAdapterType.Physical
                };
                NetworkConfiguration.AddInterfaceSetting(model);
                NetworkConfiguration.ApplyInterfaceSetting(model);
                ConsoleLogger.Log($"[wizard] network configured at {Interface}");
                HostConfiguration.SetHostAsConfigured();
                ConsoleLogger.Log("[wizard] configuration complete");
                return(HttpStatusCode.OK);
            };
        }
        /// <summary>
        /// Splits a csv line into its components.
        /// </summary>
        /// <param name="text">The comma separated line to be split into
        /// components.</param>
        /// <param name="options">The string splitting options.</param>
        /// <returns>The items, broken down as an array of strings.</returns>
        /// <exception cref="ArgumentNullException">Thrown if
        /// <paramref name="text"/> is null.</exception>
        /// <exception cref="CsvException">Thrown if the csv string is malformed.
        /// </exception>
        private static string[] SplitCsvLine(string text, StringSplitOptions options)
        {
            if (text == null) {
            throw new ArgumentNullException("text");
              }
              int start = 0;
              List<string> retVal = new List<string>();
              bool quotes = false;
              for (int i = 0; i < text.Length; i++) {
            switch (text[i]) {
              case '"':
            quotes = !quotes;
            break;

              case ',':
            if (!quotes) {
              retVal.AddRange(ExtractAndAddItem(text, start, i, options));
              start = i + 1;
            }
            break;
            }
              }
              retVal.AddRange(ExtractAndAddItem(text, start, text.Length, options));
              // Quotes opened, not closed.
              if (quotes) {
            throw new CsvException(CommonErrorMessages.QuotesNotClosedInCsvLine);
              }
              return retVal.ToArray();
        }
예제 #54
0
 /// <summary>
 /// Splits the contents of <paramref name="span"/> on the specified separator.
 /// </summary>
 /// <param name="span">The chars to split.</param>
 /// <param name="separator">The consecutive characters (string) to split on.</param>
 /// <param name="stringSplitOptions">The split options.</param>
 public static SpanSplitSequenceEnumerator <char> Split(this ReadOnlySpan <char> span, ReadOnlySpan <char> separator, StringSplitOptions stringSplitOptions = StringSplitOptions.None)
 => new SpanSplitSequenceEnumerator <char>(span, separator, stringSplitOptions);
예제 #55
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Split the ITsString into pieces separated by one of the strings in separator, and
		/// using the same options as String.Split().
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public static List<ITsString> Split(ITsString tss, string[] separator, StringSplitOptions opt)
		{
			List<ITsString> rgtss = new List<ITsString>();
			if (tss == null || tss.Length == 0 || separator == null || separator.Length == 0)
			{
				rgtss.Add(tss);
			}

			else
			{
				int ich = 0;
				while (ich < tss.Length)
				{
					int cchMatch = 0;
					int ichEnd = tss.Text.IndexOf(separator[0], ich);
					if (ichEnd < 0)
						ichEnd = tss.Length;
					else
						cchMatch = separator[0].Length;
					for (int i = 1; i < separator.Length; ++i)
					{
						int ichEnd2 = tss.Text.IndexOf(separator[i], ich);
						if (ichEnd2 < 0)
							ichEnd2 = tss.Length;
						if (ichEnd2 < ichEnd)
						{
							ichEnd = ichEnd2;
							cchMatch = separator[i].Length;
						}
					}
					int length = ichEnd - ich;
					if (length > 0 || opt == StringSplitOptions.None)
						rgtss.Add(tss.Substring(ich, length));
					ich = ichEnd + cchMatch;
				}
			}
			return rgtss;
		}
 public static List <string> SplitString(string strStringToSplit, string splitBy, StringSplitOptions splitOptions = StringSplitOptions.None)
 {
     return(strStringToSplit.Split(new string[] { splitBy }, splitOptions).ToList());
 }
예제 #57
0
 public abstract StringSpan[] Split(string separator, StringSplitOptions options);
 /// <summary>
 /// Initializes the configuration of Guilded.NET's commands.
 /// </summary>
 /// <param name="prefix">The prefix with which all commands should start</param>
 /// <param name="separators">The separators that split the command's arguments</param>
 /// <param name="splitOptions">The splitting options of the command's arguments</param>
 public CommandConfiguration(string prefix, char[] separators, StringSplitOptions splitOptions = DefaultSplitOptions) =>
 (Prefix, Separators, SplitOptions) = (prefix, separators, splitOptions);
예제 #59
0
 public abstract StringSpan[] Split(char @char, StringSplitOptions options);
예제 #60
0
 public void Execute(ref StringSplitOptions options)
 {
     options = StringSplitOptions.None;
 }