Peek() приватный Метод

private Peek ( ) : int
Результат int
Пример #1
0
        public IEnumerable<Token> Scan(string expression)
        {
            _reader = new StringReader(expression);

            var tokens = new List<Token>();
            while (_reader.Peek() != -1)
            {
                var c = (char)_reader.Peek();
                if (Char.IsWhiteSpace(c))
                {
                    _reader.Read();
                    continue;
                }

                if (Char.IsDigit(c))
                {
                    var nr = ParseNumber();
                    tokens.Add(new NumberConstantToken(nr));
                }
                else if (c == '-')
                {
                    tokens.Add(new MinusToken());
                    _reader.Read();
                }
                else if (c == '+')
                {
                    tokens.Add(new PlusToken());
                    _reader.Read();
                }
                else
                    throw new Exception("Unknown character in expression: " + c);
            }

            return tokens;
        }
Пример #2
0
        /// <summary>
        /// Converts new lines to break lines.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">text</exception>
        public static string NewLinesToBreakLines(this string text)
        {
            text.ThrowIfNull(nameof(text));

            if (String.IsNullOrWhiteSpace(text))
                return text;

            text = text.Replace(@"\r\n", Environment.NewLine)
                .Replace(@"\r", Environment.NewLine)
                .Replace(@"\n", Environment.NewLine);

            using (StringReader sr = new StringReader(text))
            using (StringWriter sw = new StringWriter(CultureConstants.InvariantCulture))
            {
                //Loop while next character exists
                while (sr.Peek() > -1)
                {
                    // Read a line from the string and writes it to an internal StringBuilder created automatically
                    sw.Write(sr.ReadLine());

                    // Adds an HTML break line as long as it's not the last line
                    if (sr.Peek() > -1)
                        sw.Write("<br>");
                }

                return sw.GetStringBuilder().ToString();
            }
        }
Пример #3
0
 /* The Method Factor checks if the next Element in the String is an Element of the Lists
 * varibles or digit or read.peek() is -1 (then theres no next element in the string) if not it has to be a "(" otherwise the expression is false
 */
 private void Factor(StringReader reader)
 {
     if (variables.Contains((char)reader.Peek()))
     {
         reader.Read();
         return;
     }
     else if (digit.Contains((char)reader.Peek()))
     {
         reader.Read();
         Constant(reader);
         return;
     }
     else if ((char)reader.Peek() == '(')
     {
         reader.Read();
         Expression(reader);
         if ((char)reader.Peek() == ')')
         {
             reader.Read();
             return;
         }
         else
         {
             throw new ParseError("\")\" expected");
         }
     }
     else if (reader.Peek() == -1) // wenn der reader -1 als nächstes zeichen sieht dann ist string zu ende gelesen
     {
         return;
     }
     else throw new ParseError("invalid factor in "+ expressionString);
 }
Пример #4
0
        public IEnumerable<Token> Scan(string code)
        {
            using (TextReader textReader = new StringReader(code))
            {
                char chr;
                string name;
                Kind keyword;
                while (textReader.Peek() != -1)
                {
                    chr = (char)textReader.Peek();

                    if (chr == '[')
                    {
                        name = ScannAttribute(textReader);
                        yield return Token.Attribute(name);
                    }
                    else if (char.IsLetter(chr))
                    {
                        name = ScanName(textReader);
                        keyword = ConvertToKeyword(name);
                        if (keyword == Kind.Name)
                            yield return Token.Name(name);
                        else
                            yield return Token.Keyword(keyword);
                    }
                    else
                        textReader.Read();
                }

                yield return Token.EOF;
            }
        }
Пример #5
0
        public static string RemoveSpaces2(string value, int length)
        {
            var stringBuilder = new StringBuilder();
            using (var stringReader = new StringReader(value))
            {
                while (stringReader.Peek() != -1)
                {
                    var ch = (char)stringReader.Peek();
                    if (char.IsWhiteSpace(ch))
                    {
                        while (char.IsWhiteSpace(ch))
                        {
                            stringReader.Read();
                            ch = (char)stringReader.Peek();
                        }

                        if (stringBuilder.Length != 0 && stringBuilder.Length < length)
                        {
                            stringBuilder.Append("%20");
                        }
                    }
                    else
                    {
                        stringBuilder.Append((char)stringReader.Read());
                    }
                }
            }

            return stringBuilder.ToString();
        }
Пример #6
0
 public static bool ReadADateTime(StringReader i_sr, out DateTime DateTime)
 {
     DateTime = new DateTime();
     string key = "";
     char ch = (char)i_sr.Peek();
     while (!IsEmptySpace(ch) && !IsToken(ch))
     {
         key += (char)i_sr.Read();
         ch = (char)i_sr.Peek();
     }
     string[] nums = key.Split('.');
     if (nums.Length != 3)
     {
         return false;
     }
     try
     {
         DateTime = new DateTime(Int32.Parse(nums[0]), Int32.Parse(nums[1]), Int32.Parse(nums[2]));
     }
     catch (FormatException)
     {
         Debug.Assert(false, "Bad DateTime Format");
     }
     catch (OverflowException)
     {
         Debug.Assert(false, "Bad DateTime Format");
     }
     return true;
 }
Пример #7
0
 private bool preProcess(int type = 1)
 {
     String input = txtInput.Text;
     StringReader sReader = new StringReader(input);
     String tmp;
     switch(type) {
         case 1:
             // postfix
             while (sReader.Peek() != -1)
             {
                 tmp = sReader.ReadLine();
                 tmp = tmp.Trim();
                 if (tmp.IndexOf(" ") > 0)
                 {
                     postfix.Clear();
                     MessageBox.Show("Please input the valid string format (separate each \"node\" with <enter> and no space is allowed in a line)", "Invalid Input!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                     return false;
                 }
                 postfix.Add(new Postfix(tmp));
             }
             break;
         case 2:
             // pseudocode
             while (sReader.Peek() != -1)
             {
                 tmp = sReader.ReadLine();
             }
             break;
     }
     return true;
 }
        // The parsing logic is based on http://www.w3.org/TR/CSS2/syndata.html.
        internal static string TransformCssFile( string sourceCssText )
        {
            sourceCssText = RegularExpressions.RemoveMultiLineCStyleComments( sourceCssText );

            var customElementsDetected = from Match match in Regex.Matches( sourceCssText, customElementPattern ) select match.Value;
            customElementsDetected = customElementsDetected.Distinct();
            var knownCustomElements = CssPreprocessingStatics.Elements.Select( ce => reservedCustomElementPrefix + ce.Name );
            var unknownCustomElements = customElementsDetected.Except( knownCustomElements ).ToList();
            if( unknownCustomElements.Any() ) {
                throw new MultiMessageApplicationException(
                    unknownCustomElements.Select( e => "\"" + e + "\" begins with the reserved custom element prefix but is not a known custom element." ).ToArray() );
            }

            using( var writer = new StringWriter() ) {
                var buffer = new StringBuilder();
                using( var reader = new StringReader( sourceCssText ) ) {
                    char? stringDelimiter = null;
                    while( reader.Peek() != -1 ) {
                        var c = (char)reader.Read();

                        // escaped quote, brace, or other character
                        if( c == '\\' ) {
                            buffer.Append( c );
                            if( reader.Peek() != -1 )
                                buffer.Append( (char)reader.Read() );
                        }

                        // string delimiter
                        else if( !stringDelimiter.HasValue && ( c == '\'' || c == '"' ) ) {
                            buffer.Append( c );
                            stringDelimiter = c;
                        }
                        else if( stringDelimiter.HasValue && c == stringDelimiter ) {
                            buffer.Append( c );
                            stringDelimiter = null;
                        }

                        // selector delimiter
                        else if( !stringDelimiter.HasValue && ( c == ',' || c == '{' ) ) {
                            writer.Write( getTransformedSelector( buffer.ToString() ) );
                            writer.Write( c );
                            buffer = new StringBuilder();
                        }
                        else if( !stringDelimiter.HasValue && c == '}' ) {
                            writer.Write( buffer.ToString() );
                            writer.Write( c );
                            buffer = new StringBuilder();
                        }

                        // other character
                        else
                            buffer.Append( c );
                    }
                }
                writer.Write( buffer.ToString() );
                return writer.ToString();
            }
        }
Пример #9
0
 /* The Method Expression calls the Method Term because the first Element of
 * a valid expression has to be a term and checks if the specification: term {(+|-) term} is fulfilled
 */
 private void Expression(StringReader reader)
 {
     Term(reader);
     while ((char)reader.Peek() == '+' || (char)reader.Peek() == '-')
     {
         reader.Read();
         Term(reader);
     }
 }
Пример #10
0
        /// <summary>
        /// Consume a string of lower case characters
        /// </summary>
        /// <param name="stream">Stream to read from</param>
        /// <param name="target">Target to read to</param>
        /// <returns>True when succesful (target contains something)
        /// </returns>
        public static bool ConsumeIdentifier(StringReader stream, out string target)
        {
            StringBuilder sbl = new StringBuilder ();

            while ((stream.Peek() >= (int)'a') && (stream.Peek() <= (int)'z'))
                sbl.Append ((char)stream.Read ());

            target = sbl.ToString();
            return target.Length > 0;
        }
Пример #11
0
        public void Load()
        {
            // Clear existing data
            lstSettings.Clear();
            lstCats.Clear();

            // Check it exists
            if (!File.Exists(strFilename)) return;

            // Read the file
            byte[] data = File.ReadAllBytes(strFilename);
            string content = ASCIIEncoding.ASCII.GetString(data);
            content = content.Replace(Environment.NewLine, "\n");

            // Set the current category
            string curCat = "Default";

            // Create a reader
            StringReader rdr = new StringReader(content);
            string parsed = "";

            // Loop
            for (char c = rdr.Peek(); c != '\0'; c = rdr.Peek())
            {
                parsed += c;

                // See what the character represents
                if (Regex.IsMatch(c.ToString(), ptnCategoryStart))
                {
                    rdr.Read();
                    curCat = rdrReadCategory(rdr);
                    lstCats.Add(curCat);
                    continue;
                }
                if (Regex.IsMatch(c.ToString(), ptnKey))
                {
                    Setting s = rdrReadSetting(rdr);
                    if (s.Value != null)
                    {
                        s.Category = curCat;
                        lstSettings.Add(s);
                    }
                    continue;
                }
                if (Regex.IsMatch(c.ToString(), ptnCommentStart))
                {
                    rdrReadComment(rdr);
                    continue;
                }

                // Must be whitespace, ignore it
                rdr.Read();
            }
        }
Пример #12
0
 public static bool ReadAKey(StringReader i_sr, out string key)
 {
     key = "";
     char ch = (char)i_sr.Peek();
     while (!IsEmptySpace(ch) && !IsToken(ch))
     {
         key += (char)i_sr.Read();
         ch = (char)i_sr.Peek();
     }
     return (key.Length > 0);
 }
Пример #13
0
        public IEnumerable<Token> Scan(string expression)
        {
            _reader = new StringReader(expression);

            while (_reader.Peek() != -1)
            {
                var c = (char)_reader.Peek();
                if (char.IsWhiteSpace(c))
                {
                    _reader.Read();
                    continue;
                }

                if (char.IsDigit(c) || c == '.')
                {
                    var value = ParseNumber();
                    yield return new NumberToken(value);
                }
                else if (c == '-')
                {
                    yield return new MinusToken();
                    _reader.Read();
                }
                else if (c == '+')
                {
                    yield return new PlusToken();
                    _reader.Read();
                }
                else if (c == '*')
                {
                    yield return new MultiplicationToken();
                    _reader.Read();
                }
                else if (c == '/')
                {
                    yield return new DivideToken();
                    _reader.Read();
                }
                else if (c == '(')
                {
                    yield return new OpenParenthesisToken();
                    _reader.Read();
                }
                else if (c == ')')
                {
                    yield return new ClosedParenthesisToken();
                    _reader.Read();
                }
                else
                    throw new Exception("Unknown character in expression: " + c);
            }
        }
Пример #14
0
        private void Prepare()
        {
            if (string.IsNullOrEmpty(_regex)) Error("Regex cannot be empty");
            var reader = new StringReader(_regex);
            var tmp = new StringBuilder(_regex.Length);

            bool range = false;
            while (reader.Peek() != -1)
            {
                char c = (char) reader.Read();
                int n = reader.Peek();
                bool escape = c == '\\' && ToEscape.Contains((char) n);
                if (escape) c = (char) reader.Read();

                bool start = !escape && c == '[';
                bool finish = !escape && c == ']';
                if (start) { range = true; tmp.Append('('); }
                else if (finish) { range = false; tmp.Remove(tmp.Length - 1, 1).Append(')'); }
                else if (!range) { tmp.AppendEscaped(escape, c); }
                else
                {
                    if (n == '-' && !escape)
                    {
                        reader.Read();
                        n = (char) reader.Peek();
                        for (char i = c; i < n; i++)
                            tmp.Append(i).Append('|');
                    }
                    else tmp.AppendEscaped(escape, c).Append('|');
                }
            }

            reader = new StringReader(tmp.ToString());
            tmp = new StringBuilder(tmp.Length * 2);
            bool printDot = false;
            while (reader.Peek() != -1)
            {
                char c = (char) reader.Read();
                int n = reader.Peek();
                bool escape = c == '\\' && ToEscape.Contains((char) n);
                if (escape) c = (char) reader.Read();

                if (printDot && !NotBefore.Contains(c) || printDot && escape)
                    tmp.Append('.');

                tmp.AppendEscaped(escape, c);
                printDot = !NotAfter.Contains(c) || escape;
            }

            _regex = tmp.ToString();
        }
Пример #15
0
	public void TestPeekRead() {
		StringReader reader = new StringReader( "Test String" );

		char c = (char)reader.Peek();
		Assert.AreEqual ('T', c, "A1");

		char read = (char)reader.Read();

		Assert.AreEqual ('T', read, "A2");

		c = (char)reader.Peek();

		Assert.AreEqual ('e', c, "A3");
	}
	public void TestPeekRead() {
		StringReader reader = new StringReader( "Test String" );

		char c = (char)reader.Peek();
		AssertEquals("A1", 'T', c );

		char read = (char)reader.Read();

		AssertEquals("A2", 'T', read );

		c = (char)reader.Peek();

		AssertEquals("A3", 'e', c );
	}
Пример #17
0
 private static string Read(StringReader reader)
 {
     var accumulator = new StringBuilder();
     accumulator.Append((char)reader.Read());
     while (reader.Peek() != -1)
     {
         if ((char)reader.Peek() == ' ')
         {
             break;
         }
         accumulator.Append((char)reader.Read());
     }
     return accumulator.ToString();
 }
Пример #18
0
        /// <summary>
        /// Parses the specified template.
        /// </summary>
        /// <param name="template">The template.</param>
        /// <returns>A <c>ReadOnlyCollection</c> containing the segments of the template.</returns>
        /// <exception cref="System.ArgumentNullException">The <paramref name="template"/> parameter is null.</exception>
        public ReadOnlyCollection<TemplateSegment> Parse(string template)
        {
            if (template == null)
            {
                throw new ArgumentNullException("template");
            }

            var segments = new List<TemplateSegment>();

            using (var reader = new StringReader(template))
            {
                var segmentType = TemplateSegmentType.PlainText;
                var segmentContent = new StringBuilder();

                int ch;
                while ((ch = reader.Read()) != -1)
                {
                    bool isOpening = !IsInsideBlock(segmentType) && ch == '<' && reader.Peek() == '%';
                    bool isClosing = IsInsideBlock(segmentType) && ch == '%' && reader.Peek() == '>';

                    if (isOpening || isClosing)
                    {
                        // Because we peeked at the next char and know it is part of the identifier we can discard it
                        reader.Read();

                        if (segmentContent.Length != 0)
                        {
                            segments.Add(new TemplateSegment(segmentType, segmentContent.ToString()));
                            segmentContent.Clear();
                        }

                        segmentType = isOpening ? TemplateSegmentType.CodeBlock : TemplateSegmentType.PlainText;
                    }
                    else
                    {
                        segmentContent.Append((char)ch);
                    }
                }

                // If there is never an opening or closing identifier, the content of the segment is considered plain text
                if (segmentContent.Length != 0)
                {
                    segments.Add(new TemplateSegment(TemplateSegmentType.PlainText, segmentContent.ToString()));
                }
            }

            return new ReadOnlyCollection<TemplateSegment>(segments);
        }
		public CommandExpression Parse(string text)
		{
			if(string.IsNullOrWhiteSpace(text))
				return null;

			CommandExpression result = null;
			CommandExpression current = null;

			using(var reader = new StringReader(text))
			{
				while(reader.Peek() > 0)
				{
					current = Parse(reader);

					if(result == null)
						result = current;
					else //线性查找命令表达式的管道链,并更新其指向
					{
						var previous = result;

						while(previous.Next != null)
						{
							previous = previous.Next;
						}

						previous.Next = current;
					}
				}
			}

			return result;
		}
Пример #20
0
    public DialogueSequence(TextAsset nodeFile)
        : this()
    {
        System.IO.StringReader sr = new System.IO.StringReader(nodeFile.text);

        while(sr.Peek() != -1 && sr.ReadLine().Trim().Equals("NODE:")) {  // Read each node in.
            string name = sr.ReadLine().Trim().Substring(6);
            string speaker = sr.ReadLine().Trim().Substring(9);
            string text = sr.ReadLine().Trim().Substring(6);
            string tmp;

            while( (tmp = sr.ReadLine().Trim()) != "ENDTEXT") {
                text += tmp + " ";
            }

            DialogueNode newNode = new DialogueNode(name, speaker, text);

            while( (tmp = sr.ReadLine().Trim()) == "OPTION:" ) {
                name = sr.ReadLine().Trim();
                text = sr.ReadLine().Trim();
                options.Add( new Option{ from = newNode.name, to = name, description = text } );
            }
            this.AddNode(newNode);
        }

        //TODO Verify that all options are valid.
    }
Пример #21
0
        static List <AssetData> Load()
        {
            var assetlist = new List <AssetData>();

            var files = Directory.GetFiles(".", "ImportPackages*.imp", SearchOption.AllDirectories);

            foreach (var file in files)
            {
                var text       = File.ReadAllText(file);
                var textReader = new System.IO.StringReader(text);
                var url        = textReader.ReadLine();

                var assetData = new AssetData();
                assetData.asseturl = url;
                assetlist.Add(assetData);

                while (textReader.Peek() > -1)
                {
                    var strs            = textReader.ReadLine().Split(',');
                    var guid            = strs[1];
                    var requestFilePath = strs[0];

                    var filePath = AssetDatabase.GUIDToAssetPath(guid);
                    if (string.IsNullOrEmpty(filePath) || File.Exists(filePath) == false)
                    {
                        assetData.pathList.Add(requestFilePath);
                    }
                }
            }

            return(assetlist);
        }
Пример #22
0
    /// <summary>
    /// 文章、単語読み込み
    /// </summary>
    private void ReadText()
    {
        TextAsset csvfile_quest      = Resources.Load("Minigame/Hacking/Quest") as TextAsset;
        TextAsset csvfile_answer     = Resources.Load("Minigame/Hacking/Answer") as TextAsset;
        TextAsset csvfile_folder_ans = Resources.Load("Minigame/Hacking/Folder_answer") as TextAsset;

        System.IO.StringReader stren_quest      = new System.IO.StringReader(csvfile_quest.text);
        System.IO.StringReader stren_answer     = new System.IO.StringReader(csvfile_answer.text);
        System.IO.StringReader stren_folder_ans = new System.IO.StringReader(csvfile_folder_ans.text);

        while (stren_quest.Peek() > -1)
        {
            str_quest  = stren_quest.ReadLine();
            str_answer = stren_answer.ReadLine();
            string[] s_a = str_answer.Split(',');
            string[] s_q = str_quest.Split(',');

            for (int i = 0; i < s_a.Length; i++)
            {
                Answer_list.Add(s_a[i]);
                Quest_list.Add(s_q[i]);
            }
        }
        while (stren_folder_ans.Peek() > -1)
        {
            str_folder_ans = stren_folder_ans.ReadLine();
            string[] s_f = str_folder_ans.Split(',');
            for (int i = 0; i < s_f.Length; i++)
            {
                Folder_ans_list.Add(s_f[i]);
            }
        }
    }
Пример #23
0
    /// <summary>
    /// リソースのロード
    /// </summary>
    /// <param name="path">リソースのパス</param>
    /// <param name="isJoinLine">trueなら改行を結合する</param>
    /// <returns></returns>
    private bool Load(string path, bool isJoinLine)
    {
        if (path == null)
        {
            throw new System.ArgumentNullException();
        }

        this.resourcePath = path;
        TextAsset textAsset = (TextAsset)Resources.Load(resourcePath);

        if (textAsset == null)
        {
            // ロードできなかった
            throw new UnityResourceNotFoundException();
        }

        text = "";
        if (isJoinLine)
        {
            // 改行も考慮して取得
            System.IO.StringReader reader = new System.IO.StringReader(textAsset.text);
            while (reader.Peek() != -1)
            {
                // 1行ずつ読み込み
                string line = reader.ReadLine();
                text += line;
            }
        }
        else
        {
            text = textAsset.text;
        }
        return(true);
    }
Пример #24
0
        public void AddExpression(string name, string regex)
        {
            using (var stream = new StringReader(InfixToPostfix.Convert(regex)))
            {
                while (stream.Peek() != -1)
                {
                    var c = (char) stream.Read();
                    switch (c)
                    {
                        case '.': _stack.Concatenate(); break;
                        case '|': _stack.Unite(); break;
                        case '*': _stack.Iterate(); break;
                        case '+': _stack.AtLeast(); break;
                        case '?': _stack.Maybe(); break;
                        default:
                            var a = new NFA<char>();
                            a.AddTransition(a.Start, new State(), c == '\\' ? Escape((char) stream.Read()) : c);
                            _stack.Push(a);
                            break;
                    }
                }

                var top = _stack.Peek();
                top.LastAdded.Final = true;
                top.SetName(top.LastAdded, name);
            }
        }
Пример #25
0
        public PatchInfo(string name, string info)
        {
            if (name.Contains("_to_"))
            {
                var split = name.Split(new string[] { "_to_" }, StringSplitOptions.None);
                StartVersion = int.Parse(split[0]);
                EndVersion   = int.Parse(split[1]);
            }
            else
            {
                StartVersion = 0;
                EndVersion   = int.Parse(new string(name.TakeWhile(c => c != '_').ToArray()));
            }

            Files = new List <PatchFileInfo>();

            using (var r = new System.IO.StringReader(info))
            {
                r.ReadLine();                 // Count

                while (r.Peek() != -1)
                {
                    var line = r.ReadLine();
                    if (string.IsNullOrWhiteSpace(line))
                    {
                        continue;
                    }

                    var parts = line.Split(new string[] { ", " }, StringSplitOptions.None);
                    Files.Add(new PatchFileInfo(parts[0], int.Parse(parts[1]), parts[2]));
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="text"></param>
        public ImapIdleCommandMessageReceivedEventArgs(String text)
        {
            Match m = null;
            ImapIdleCommandMessageType tp = ImapIdleCommandMessageType.Exists;

            this.Done = false;
            this.Text = text;

            StringReader sr = new StringReader(text);
            while (sr.Peek() > -1)
            {
                var line = sr.ReadLine();
                if (line.StartsWith("+ idling", StringComparison.OrdinalIgnoreCase) == true)
                {
                    _MessageList.Add(new ImapIdleCommandMessage(ImapIdleCommandMessageType.Idling, -1));
                }
                else
                {
                    m = RegexList.Message.Match(line);
                    if (String.IsNullOrEmpty(m.Value) == true) { continue; }
                    switch (m.Groups["Type"].Value)
                    {
                        case "EXISTS": tp = ImapIdleCommandMessageType.Exists; break;
                        case "EXPUNGE": tp = ImapIdleCommandMessageType.Expunge; break;
                        default: continue;
                    }
                    _MessageList.Add(new ImapIdleCommandMessage(tp, Int32.Parse(m.Groups["Number"].Value)));
                }
            }
        }
Пример #27
0
        /// <summary>
        /// Loads data from csv file into List of PodatakViewModels to show in grid.
        /// </summary>
        /// <param name="filePath">Csv file path (directory + "podaci.csv")</param>
        /// <returns>List</returns>
        private async Task <List <PodatakViewModel> > LoadCsvDataFrom(string filePath)
        {
            List <PodatakViewModel> pom = new List <PodatakViewModel>();

            if (System.IO.File.Exists(filePath))
            {
                using (System.IO.StreamReader objReader = new System.IO.StreamReader(filePath, System.Text.Encoding.UTF8))
                {
                    var contents = await objReader.ReadToEndAsync();

                    using (System.IO.StringReader strReader = new System.IO.StringReader(contents))
                    {
                        do
                        {
                            var textLine = await strReader.ReadLineAsync();

                            if (textLine != string.Empty)
                            {
                                pom.Add(new PodatakViewModel(
                                            textLine.Split(';')
                                            ));
                            }
                        } while (strReader.Peek() != -1);
                    }
                }
            }

            return(pom);
        }
Пример #28
0
 public static string Trimall(this string value)
 {
     value = value.Trim();
     var output = new StringBuilder();
     using (var reader = new StringReader(value))
     {
         while (true)
         {
             var next = reader.Peek();
             if (next < 0) break;
             var c = (char)next;
             if (c == '"')
             {
                 ReadQuotedString(output, reader);
                 continue;
             }
             if (char.IsWhiteSpace(c))
             {
                 ReadWhitespace(output, reader);
                 continue;
             }
             output.Append((char)reader.Read());
         }
     }
     return output.ToString();
 }
Пример #29
0
        public string format(string text)
        {
            reader = new StringReader(text);

            int cache;

            while((cache = reader.Peek()) != -1)
            {
                if(cache == '%')
                {
                    reader.Read();
                    string c;
                    if((c = controlIdentify()) != null)
                    {
                        builder.Append(c);
                    }else
                    {
                        break;
                    }
                }
                else
                {
                    builder.Append((char)reader.Read());
                }
            }

            return builder.ToString();
        }
 public void ReadWord_EmptyString()
 {
     IO.StringReader reader = new IO.StringReader("");
     string word = TextReader.ReadWord(reader);
     Assert.AreEqual("", word);
     Assert.AreEqual(-1, reader.Peek());
 }
Пример #31
0
        static List<AssetData> Load()
        {
            var assetlist = new List<AssetData>();

            var files = Directory.GetFiles("Assets", "ImportPackages*.imp", SearchOption.AllDirectories);
            foreach( var file in files ){
                var text = File.ReadAllText(file);
                var textReader = new System.IO.StringReader(text);
                var url = textReader.ReadLine();

                var assetData = new AssetData();
                assetData.asseturl = url;
                assetlist.Add(assetData);

                while( textReader.Peek() > -1 ){
                    var strs = textReader.ReadLine().Split(',');
                    var guid = strs[1];
                    var requestFilePath = strs[0];

                    var filePath = AssetDatabase.GUIDToAssetPath( guid );
                    if( string.IsNullOrEmpty( filePath ) || File.Exists(filePath) == false ){
                        assetData.pathList.Add(requestFilePath);
                    }
                }
            }

            return assetlist;
        }
        public void Parse(string header) {
            var buffer = new StringBuilder();
            var reader = new StringReader(header);
            var parameterText = new StringBuilder();

            bool withinQuotes = false;

            do {
                var c = (char)reader.Read();

                if (!String.IsNullOrEmpty(Scheme))
                    parameterText.Append(c);

                if (c == '"') {
                    withinQuotes = !withinQuotes;
                    continue;
                }

                if (char.IsWhiteSpace(c) && buffer.Length == 0 && !withinQuotes)
                    continue;

                if ((c == ',' || char.IsWhiteSpace(c)) && buffer.Length > 0 && !withinQuotes) {
                    // end of token                    
                    ReadToken(buffer);
                    continue;
                }

                buffer.Append(c);
            } while (reader.Peek() != -1);

            ReadToken(buffer);

            _parameterText = parameterText.ToString();
        }
Пример #33
0
        private static Exception CreateFromDslCore(string format)
        {
            List<Tuple<string, string>> identifiers = new List<Tuple<string,string>>();

            StringBuilder token = new StringBuilder();
            StringReader reader = new StringReader(format);

            while (reader.Peek() != -1)
            {
                char c = (char)reader.Read();
                if (c == '|')
                {
                    AddIdentifier(identifiers, token);
                    continue;
                }

                if (c == '(')
                {
                    string dsl = ReadToNextMatchingParenthesis(reader);

                    AddIdentifier(identifiers, token, dsl);
                    continue;
                }

                token.Append(c);
            }

            AddIdentifier(identifiers, token);

            return CreateFromList(identifiers);
        }
        public void AppendRTF(string rtf)
        {
            StringReader sr = new StringReader(rtf);
            int c = sr.Peek();
            if (c == '\\')
            {
                sr.Read();
            }

            using (this._builder.FormatLock())
            {
                while (c != Eof)
                {
                    switch (c)
                    {
                        case '\\':
                            c = this.TokenAction(sr);
                            break;
                        default:
                            c = this.ReadString(sr, c);
                            break;
                    }
                }
            }
        }
Пример #35
0
 /* The Method Constant checks if the next element of the text is an Element of
 * the List digit then it gets read
 */
 private void Constant(StringReader reader)
 {
     while (digit.Contains((char)reader.Peek()))
     {
         reader.Read();
     }
 }
Пример #36
0
        /// <summary>
        /// Converts a string to a number (used by parseFloat).
        /// </summary>
        /// <param name="input"> The string to convert. </param>
        /// <returns> The result of parsing the string as a number. </returns>
        internal static double ParseFloat(string input)
        {
            var reader = new System.IO.StringReader(input);

            // Skip whitespace and line terminators.
            while (IsWhiteSpaceOrLineTerminator(reader.Peek()))
            {
                reader.Read();
            }

            // The number can start with a plus or minus sign.
            bool negative  = false;
            int  firstChar = reader.Read();

            switch (firstChar)
            {
            case '-':
                negative  = true;
                firstChar = reader.Read();
                break;

            case '+':
                firstChar = reader.Read();
                break;
            }

            // Infinity or -Infinity are also valid.
            if (firstChar == 'I')
            {
                var nfinityString = reader.ReadToEnd();
                if (nfinityString == null)
                {
                    throw new InvalidOperationException("Reader returned null.");
                }

                if (nfinityString.StartsWith("nfinity", StringComparison.Ordinal))
                {
                    return(negative ? double.NegativeInfinity : double.PositiveInfinity);
                }
            }

            // Empty strings return NaN.
            if ((firstChar < '0' || firstChar > '9') && firstChar != '.')
            {
                return(double.NaN);
            }

            // Parse the number.
            NumberParser.ParseCoreStatus status;
            var result = NumberParser.ParseCore(reader, (char)firstChar, out status, false, false);

            // Handle various error cases.
            if (status == ParseCoreStatus.NoDigits)
            {
                return(double.NaN);
            }

            return(negative ? -result : result);
        }
Пример #37
0
 /// <summary>
 /// 錬成csv読み込み
 /// </summary>
 private void ReadText()
 {
     csvFile = Resources.Load("CSV/alchemyList") as TextAsset;
     System.IO.StringReader reader = new System.IO.StringReader(csvFile.text);
     while (reader.Peek() >= -1)
     {
     }
 }
Пример #38
0
        public void ReadWord_TrailingWhitespace()
        {
            IO.StringReader reader = new IO.StringReader("<-o->\n \t");
            string          word   = TextReader.ReadWord(reader);

            Assert.AreEqual("<-o->", word);
            Assert.AreEqual((int)'\n', reader.Peek());
        }
Пример #39
0
        public void ReadWord_LeadingWhitespace()
        {
            IO.StringReader reader = new IO.StringReader(" \t987");
            string          word   = TextReader.ReadWord(reader);

            Assert.AreEqual("", word);
            Assert.AreEqual((int)' ', reader.Peek());
        }
Пример #40
0
        public void ReadWord_JustWord()
        {
            IO.StringReader reader = new IO.StringReader("ABCs");
            string          word   = TextReader.ReadWord(reader);

            Assert.AreEqual("ABCs", word);
            Assert.AreEqual(-1, reader.Peek());
        }
Пример #41
0
        public void ReadWord_EmptyString()
        {
            IO.StringReader reader = new IO.StringReader("");
            string          word   = TextReader.ReadWord(reader);

            Assert.AreEqual("", word);
            Assert.AreEqual(-1, reader.Peek());
        }
Пример #42
0
 public void MultipleWords()
 {
     string[]        colors = new string[] { "red", "blue", "green", "white" };
     IO.StringReader reader = new IO.StringReader(string.Join(" ", colors));
     foreach (string color in colors)
     {
         TextReader.SkipWhitespace(reader);
         Assert.AreEqual(color, TextReader.ReadWord(reader));
     }
     Assert.AreEqual(-1, reader.Peek());
 }
Пример #43
0
    /// <summary>
    /// ボスのテキスト読み込み
    /// </summary>
    private void ReadBossText()
    {
        TextAsset csv_file = Resources.Load("Minigame/Hacking/Hack_BossText") as TextAsset;

        System.IO.StringReader str_text = new System.IO.StringReader(csv_file.text);
        while (str_text.Peek() > -1)
        {
            str_line = str_text.ReadLine();
            Boss_text.Add(str_line);
            maxLine++;
        }
    }
Пример #44
0
        private void button_Click(object sender, EventArgs e)
        {
            if (sender == button1)
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = "テキストファイル|*.txt";

                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    /* StreamReader sr = new StreamReader(ofd.FileName, System.Text.Encoding.Default);
                     * textBox1.Text = sr.ReadToEnd();
                     * sr.Close();*/
                    ReadCsv(ofd);
                }
            }
            else if (sender == button2)
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "テキストファイル|*.txt";

                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    StreamWriter sw = new StreamWriter(sfd.FileName);

                    System.IO.StringReader rs =
                        new System.IO.StringReader(textBox1.Text);

                    int NLcnt = 0;
                    while (rs.Peek() > -1)
                    {
                        var line = rs.ReadLine();

                        if (line.Length == 0)
                        {
                            if (NLcnt == 0)
                            {
                                sw.WriteLine();
                                NLcnt++;
                            }
                        }
                        else
                        {
                            sw.Write(line + ",");
                            NLcnt = 0;
                        }
                    }


                    rs.Close();
                    sw.Close();
                }
            }
        }
Пример #45
0
        //翻訳後のテキストをリストに格納
        public List <string> TextToArray(string text)
        {
            List <string> list = new List <string>();

            System.IO.StringReader rs = new System.IO.StringReader(text);
            while (rs.Peek() > -1)
            {
                list.Add(rs.ReadLine());
            }
            rs.Close();

            return(list);
        }
Пример #46
0
 internal DotNetVM(string Code, Language Lang)
 {
     System.IO.StringReader Sr = new System.IO.StringReader(Code);
     string[] Lines            = new string[0];
     while (Sr.Peek() != -1)
     {
         string[] tmp = new string[Lines.Length + 1];
         Lines.CopyTo(tmp, 0);
         tmp[Lines.Length] = Sr.ReadLine();
         Lines             = tmp;
     }
     Engine = InitializeEngine(Lines, Lang);
 }
Пример #47
0
    void _Localization(string text)
    {
        LocalizationDataList localizationDataList = new LocalizationDataList();

        using (System.IO.StringReader reader = new System.IO.StringReader(text))
        {
            while (reader.Peek() != -1)
            {
                string line = reader.ReadLine();

                if (line.Length < 3)
                {
                    continue;
                }

                string sId = line.Substring(0, 3);
                int    id;
                try
                {
                    id = int.Parse(sId);
                }
                catch
                {
                    continue;
                }

                string[] split = line.Split('	');
                if (split.Length < 4)
                {
                    Debug.LogError(line);
                }

                Debug.Log(id + ": " + split[2] + " " + split[3]);

                LocalizationData data = new LocalizationData();
                data.id  = id;
                data.eng = split[2];
                data.cht = split[3];

                localizationDataList.list.Add(data);
            }
        }

        string localText = JsonUtility.ToJson(localizationDataList);
        string path      = Path.Combine(Application.dataPath, "Data");

        File.WriteAllText(path + "localization.json", localText);
    }
Пример #48
0
        /// <summary>
        /// Parses a code snippet string of code to a list of strings of code per instance
        /// </summary>
        /// <param name="file">String containing code from textarea</param>
        /// <returns>List of strings with a line of code in each instance</returns>
        private List <string> SnippetRead(string file)
        {
            var result  = new List <string>();
            int counter = 1;

            using (System.IO.StringReader reader = new System.IO.StringReader(file)) //Read using reader so that it iterates and we can add line numbers
            {
                while (reader.Peek() >= 0)
                {
                    result.Add("<b>Line " + counter + " |</b> " + @reader.ReadLine());
                    counter++;
                }
            }

            return(result);
        }
Пример #49
0
    internal DotNetVM(string Content, Language Lang = Language.CSharp, string FileName = null, bool Debug = false)
    {
        if (System.IO.File.Exists(Content))
        {
            DllInitialize(Content);
            return;
        }

        System.IO.StringReader Sr = new System.IO.StringReader(Content);
        string[] Lines            = new string[0];
        while (Sr.Peek() != -1)
        {
            string[] tmp = new string[Lines.Length + 1];
            Lines.CopyTo(tmp, 0);
            tmp[Lines.Length] = Sr.ReadLine();
            Lines             = tmp;
        }
        Assembly = InitializeEngine(Lines, Lang, FileName, Debug);
    }
Пример #50
0
    public void readJson(string filePath)
    {
        if (File.Exists(filePath))
        {
            string dataAsJson = File.ReadAllText(filePath);
            using (System.IO.StringReader reader = new System.IO.StringReader(dataAsJson))
            {
                while (reader.Peek() != -1)
                {
                    string songInfo       = reader.ReadLine();
                    string chartDataPath1 = reader.ReadLine();
                    string chartDataPath2 = reader.ReadLine();
                    string chartDataPath3 = reader.ReadLine();

                    print(songInfo);
                    print(chartDataPath1);
                    print(chartDataPath2);
                    print(chartDataPath3);
                    Song  newSong   = JsonUtility.FromJson <Song>(songInfo);
                    Chart newChart1 = JsonUtility.FromJson <Chart>(chartDataPath1);
                    Chart newChart2 = JsonUtility.FromJson <Chart>(chartDataPath2);
                    Chart newChart3 = JsonUtility.FromJson <Chart>(chartDataPath3);
                    newSong.chartDataList.Add(newChart1);
                    newSong.chartDataList.Add(newChart2);
                    newSong.chartDataList.Add(newChart3);
                    songList.Add(newSong);

                    print(newSong.ToString());
                    print(newChart1.ToString());
                    print(newChart2.ToString());
                    print(newChart3.ToString());
                }
                foreach (Song song in songList)
                {
                    songPlateList.Add(createSongPlate(song));
                }
            }
        }
        else
        {
            print("Cannot Find Json File");
        }
    }
Пример #51
0
        public Tuple <int, int, int> getSummary(string output)
        {
            try
            {
                System.IO.StringReader rs = new System.IO.StringReader(output);
                string buf   = rs.ReadLine();
                int    count = int.Parse(buf);
                int    move  = 0;
                if (count > problemInfo.allow)
                {
                    appendLog("選択回数オーバー");
                    return(null);
                }
                List <int>         sx = new List <int>(), sy = new List <int>();
                List <List <int> > moves = new List <List <int> >();

                while (rs.Peek() > -1)
                {
                    buf = rs.ReadLine(); // さわりはじめの場所
                    sx.Add(hexToDec(buf[0]));
                    sy.Add(hexToDec(buf[1]));
                    buf   = rs.ReadLine(); // 何回続く?(要らない情報)
                    move += int.Parse(buf);
                    buf   = rs.ReadLine(); // 実際の操作列
                    moves.Add(new List <int>());
                    for (int i = 0; i < buf.Length; i++)
                    {
                        const string table = "URDL";
                        int          idx   = table.IndexOf(buf[i]);
                        moves[moves.Count - 1].Add(idx);
                    }
                }

                int total = count * problemInfo.selectCost + move * problemInfo.swapCost;
                return(new Tuple <int, int, int>(count, move, total));
            }
            catch
            {
                appendLog("ソルバの出力が異常です。");
                return(null);
            }
        }
Пример #52
0
    private void LoadWords()
    {
        TextAsset file = Resources.Load("Words/" + fileName) as TextAsset; //load file from resources

        if (file == null)
        {
            Debug.LogError("Failed to load words. At TypingScript.LoadWords(void)");
        }

        System.IO.StringReader reader = new System.IO.StringReader(file.text); //process string
        if (reader == null)
        {
            Debug.LogError("Assets/Resources/Words/" + fileName + " Not found! At TypingScript.LoadWords(void)");
        }

        while (reader.Peek() >= 0)
        {
            wordBank.Add(reader.ReadLine());
        }
    }
        /// <summary>
        /// ノードをHTMLデータに変換する
        /// </summary>
        /// <returns></returns>
        static private void ToHTML(QuartetEditorDescriptionItem item, Dictionary <QuartetEditorDescriptionItem, string> idDictionary, StringBuilder result, int level)
        {
            // タイトルを変換
            int h = level > 6 ? 6 : level;

            result.AppendLine(string.Format("<h{0} id=\"{2}\">{1}</h{0}>", h, HttpUtility.HtmlEncode(item.Name), idDictionary[item]));

            // コンテンツ変換
            result.AppendLine(string.Format("<p class=\"Level{0}\">", level));
            System.IO.StringReader rs = new System.IO.StringReader(item.Content.TrimEnd());
            while (rs.Peek() > -1)
            {
                result.AppendLine(string.Format(@"{0}<br>", HttpUtility.HtmlEncode(rs.ReadLine())));
            }
            result.AppendLine(@"</p>");

            foreach (var child in item.Children)
            {
                ToHTML(child, idDictionary, result, level + 1);
            }
        }
Пример #54
0
    static void initCachedDict()
    {
        cacheClientStringDict.Clear();
        string    fileName = "ClientString_jpn";
        TextAsset text     = Resources.Load <TextAsset>("Common/" + fileName);

        System.IO.StringReader stringReader = new System.IO.StringReader(text.text);
        int index = 0; string[] temp; string line;

        while (stringReader.Peek() > -1)
        {
            line = stringReader.ReadLine();
            if ("" != line)
            {
                temp = line.Split(",".ToCharArray(), 2);
                var dataPair = new LocalizeDataPair();
                dataPair.key       = index;
                dataPair.keyString = temp[0];
                cacheClientStringDict[temp[1].Replace("\\n", "\n")] = dataPair;
                index++;
            }
        }
    }
Пример #55
0
        public static string Precompile(System.IO.StringReader source)
        {
            string codes = "";

            while (source.Peek() != -1)
            {
                string line = source.ReadLine();
                line += ',';

                var comment = line.IndexOf(',');

                line = line.Substring(0, comment);
                line = line.Trim(" \t\r\n".ToCharArray());

                if (line == null || line == "")
                {
                    continue;
                }

                codes += line;
            }

            return(codes);
        }
Пример #56
0
        /// <summary>
        /// Converts a string to an integer (used by parseInt).
        /// </summary>
        /// <param name="radix"> The numeric base to use for parsing.  Pass zero to use base 10
        /// except when the input string starts with '0' in which case base 16 or base 8 are used
        /// instead. </param>
        /// <param name="allowOctal"> <c>true</c> if numbers with a leading zero should be parsed
        /// as octal numbers. </param>
        /// <returns> The result of parsing the string as a integer. </returns>
        internal static double ParseInt(string input, int radix, bool allowOctal)
        {
            var reader     = new System.IO.StringReader(input);
            int digitCount = 0;

            // Skip whitespace and line terminators.
            while (IsWhiteSpaceOrLineTerminator(reader.Peek()))
            {
                reader.Read();
            }

            // Determine the sign.
            double sign = 1;

            if (reader.Peek() == '+')
            {
                reader.Read();
            }
            else if (reader.Peek() == '-')
            {
                sign = -1;
                reader.Read();
            }

            // Hex prefix should be stripped if the radix is 0, undefined or 16.
            bool stripPrefix = radix == 0 || radix == 16;

            // Default radix is 10.
            if (radix == 0)
            {
                radix = 10;
            }

            // Skip past the prefix, if there is one.
            if (stripPrefix == true)
            {
                if (reader.Peek() == '0')
                {
                    reader.Read();
                    digitCount = 1;     // Note: required for parsing "0z11" correctly (when radix = 0).

                    int c = reader.Peek();
                    if (c == 'x' || c == 'X')
                    {
                        // Hex number.
                        reader.Read();
                        radix = 16;
                    }

                    if (c >= '0' && c <= '9' && allowOctal == true)
                    {
                        // Octal number.
                        radix = 8;
                    }
                }
            }

            // Calculate the maximum number of digits before arbitrary precision arithmetic is
            // required.
            int maxDigits = (int)Math.Floor(53 / Math.Log(radix, 2));

            // Read numeric digits 0-9, a-z or A-Z.
            double result    = 0;
            var    bigResult = BigInteger.Zero;

            while (true)
            {
                int numericValue = -1;
                int c            = reader.Read();
                if (c >= '0' && c <= '9')
                {
                    numericValue = c - '0';
                }
                if (c >= 'a' && c <= 'z')
                {
                    numericValue = c - 'a' + 10;
                }
                if (c >= 'A' && c <= 'Z')
                {
                    numericValue = c - 'A' + 10;
                }
                if (numericValue == -1 || numericValue >= radix)
                {
                    break;
                }
                if (digitCount == maxDigits)
                {
                    bigResult = BigInteger.FromDouble(result);
                }
                result = result * radix + numericValue;
                if (digitCount >= maxDigits)
                {
                    bigResult = BigInteger.MultiplyAdd(bigResult, radix, numericValue);
                }
                digitCount++;
            }

            // If the input is empty, then return NaN.
            if (digitCount == 0)
            {
                return(double.NaN);
            }

            // Numbers with lots of digits require the use of arbitrary precision arithmetic to
            // determine the correct answer.
            if (digitCount > maxDigits)
            {
                return(RefineEstimate(result, 0, bigResult) * sign);
            }

            return(result * sign);
        }
Пример #57
0
        /// <summary>
        /// Converts a string to a number (used in type coercion).
        /// </summary>
        /// <returns> The result of parsing the string as a number. </returns>
        internal static double CoerceToNumber(string input)
        {
            var reader = new System.IO.StringReader(input);

            // Skip whitespace and line terminators.
            while (IsWhiteSpaceOrLineTerminator(reader.Peek()))
            {
                reader.Read();
            }

            // Empty strings return 0.
            int firstChar = reader.Read();

            if (firstChar == -1)
            {
                return(0.0);
            }

            // The number can start with a plus or minus sign.
            bool negative = false;

            switch (firstChar)
            {
            case '-':
                negative  = true;
                firstChar = reader.Read();
                break;

            case '+':
                firstChar = reader.Read();
                break;
            }

            // Infinity or -Infinity are also valid.
            if (firstChar == 'I')
            {
                string restOfString1 = reader.ReadToEnd();
                if (restOfString1.StartsWith("nfinity", StringComparison.Ordinal) == true)
                {
                    // Check the end of the string for junk.
                    for (int i = 7; i < restOfString1.Length; i++)
                    {
                        if (IsWhiteSpaceOrLineTerminator(restOfString1[i]) == false)
                        {
                            return(double.NaN);
                        }
                    }
                    return(negative ? double.NegativeInfinity : double.PositiveInfinity);
                }
            }

            // Return NaN if the first digit is not a number or a period.
            if ((firstChar < '0' || firstChar > '9') && firstChar != '.')
            {
                return(double.NaN);
            }

            // Parse the number.
            NumberParser.ParseCoreStatus status;
            double result = NumberParser.ParseCore(reader, (char)firstChar, out status, allowHex: true, allowOctal: false);

            // Handle various error cases.
            switch (status)
            {
            case ParseCoreStatus.NoDigits:
            case ParseCoreStatus.NoExponent:
                return(double.NaN);
            }

            // Check the end of the string for junk.
            string restOfString2 = reader.ReadToEnd();

            for (int i = 0; i < restOfString2.Length; i++)
            {
                if (IsWhiteSpaceOrLineTerminator(restOfString2[i]) == false)
                {
                    return(double.NaN);
                }
            }

            return(negative ? -result : result);
        }
Пример #58
0
        /// <summary>
        /// CSV形式のデータを変換
        /// </summary>
        /// <param name="text"></param>
        /// <param name="isMap"></param>
        /// <returns></returns>
        public static JsonData ConvertCSVToTreeData(string text, bool isMap = false)
        {
            string[] header = null;

            List <string[]> csvData = new List <string[]>();

            System.IO.StringReader reader = new System.IO.StringReader(text);

            // 1行目は型名の情報が入っている
            string line = reader.ReadLine();

            if (line.Contains("\t"))
            {
                header = line.Split('\t');
            }
            else
            {
                header = line.Split(',');
            }
            // 必要なデータ数
            int need = header.Length;


            List <string> values = new List <string>();

            System.Text.StringBuilder builder = new System.Text.StringBuilder();

            //AppDebug.Log ("header" + line);
            //AppDebug.Log ("カラム数:" + header.Length);
            while (reader.Peek() > -1)
            {
                values.Clear();
                //builder.Append(reader.ReadLine());
                builder.AppendLine(reader.ReadLine()); // 改行を維持する

                line = builder.ToString();

                // Clearが無いので、Removeで全削除
                builder.Remove(0, builder.Length);


                //csvでタブかカンマで区切られた文字を配列にして取得
                string[] addValues = GetCSVSplitText(line);

                //最初の1行は全件追加
                values.AddRange(addValues);
                // データ数をチェック
                int count = values.Count;

                //AppDebug.Log ("line:" + line);
                //AppDebug.Log ("カラム数:" + values.Count);

                //改行コードにより途中で文が途切れた場合の為に、データ区切りの数が満たない場合は次の行も見る
                while (count < need)
                {
                    //すでに可読の文字がない場合は終了
                    if (reader.Peek() == -1)
                    {
                        break;
                    }

                    builder.AppendLine(reader.ReadLine()); // 改行を維持する
                    line = builder.ToString();

                    // Clearが無いので、Removeで全削除
                    builder.Remove(0, builder.Length);

                    //csvでタブかカンマで区切られた文字を配列にして取得
                    addValues = GetCSVSplitText(line);

                    if (addValues.Length > 0)
                    {
                        //addValues[0] については前の行の文字とくっつける
                        values[values.Count - 1] += addValues[0];

                        //それ以外については後ろに追加
                        for (int i = 1; i < addValues.Length; i++)
                        {
                            values.Add(addValues[i]);
                        }
                    }

                    count = values.Count;


                    //AppDebug.Log ("addNext:" + line);
                    //AppDebug.Log ("カラム数:" + values.Count);
                }

                if (values.Count >= need)
                {
                    csvData.Add(values.ToArray());
                }
            }

            //AppDebug.Log ("csvData.Count=" + csvData.Count);

            JsonData retTreeData;

            //データ件数が1でMap設定のデータであればMapとして返却する
            if (csvData.Count == 1 && isMap)
            {
                retTreeData = new JsonData();
                string[] datas = csvData[0];

                //for (int i = 0; i < datas.Length; i++)
                for (int i = 0; i < need; i++)
                {
                    string data  = datas[i].Trim();
                    string title = header[i].Trim();
                    retTreeData[title] = (JsonData)data;
                }
            }
            else
            {
                //データ件数が1より多い場合は問答無用でArrayになる
                retTreeData = new JsonData();

                foreach (string[] datas in csvData)
                {
                    JsonData tree = new JsonData();
                    for (int i = 0; i < need; i++)
                    {
                        string data  = datas[i].Trim();
                        string title = header[i].Trim();
                        tree[title] = (JsonData)data;
                    }

                    retTreeData.Add(tree);
                }
            }
            return(retTreeData);
        }
Пример #59
0
        static public List <CommentNode> parseComment(string comment)
        {
            List <CommentNode> result = new List <CommentNode>();

            System.IO.StringReader rs      = new System.IO.StringReader(comment);
            CommentNode            current = new CommentNode(CommentType.SUMMARY, "");

            result.Add(current);
            while (rs.Peek() >= 0)
            {
                string line = rs.ReadLine();
                line = Regex.Replace(line, "^[ \t]*\\*[ \t]*", "");        // 行頭の * を取り除く
                line = Regex.Replace(line, "^[ \t]*", "");                 // 行頭のスペースを取り除く
                line = Regex.Replace(line, "-{4,}", "");                   // -の4回以上の繰り返しを取り除く
                if (Regex.Match(line, "^@param").Success)
                {
                    Match match;
                    if ((match = Regex.Match(line, "^@param[ \t]*([^ \t]+)[ \t]+(.+)")) != Match.Empty)
                    {
                        string name = match.Groups[1].Value;
                        string body = match.Groups[2].Value;
                        if (current.Type == CommentType.PARAM && current.Name == name)
                        {
                            if (current.Body.Length > 0)
                            {
                                current.Body += "\\n" + body;
                            }
                            else
                            {
                                current.Body = body;
                            }
                        }
                        else
                        {
                            current = new CommentNode(CommentType.PARAM, name, body);
                            result.Add(current);
                        }
                    }
                    else
                    {
                        string body = Regex.Replace(line, "^@param[ \t]*", "");                           // 先頭部分を削除
                        current = new CommentNode(CommentType.PARAM, body);
                        result.Add(current);
                    }
                }
                else if (Regex.Match(line, "^@return").Success)
                {
                    string body = Regex.Replace(line, "^@return[ \t]*", "");
                    current = new CommentNode(CommentType.RETURN, body);
                    result.Add(current);
                }
                else if (Regex.Match(line, "^@throw").Success)
                {
                    string body = Regex.Replace(line, "^@throw[ \t]*", "");
                    current = new CommentNode(CommentType.THROW, body);
                    result.Add(current);
                }
                else if (Regex.Match(line, "^@author").Success)
                {
                    string body = Regex.Replace(line, "^@author[ \t]*", "");
                    current = new CommentNode(CommentType.AUTHOR, body);
                    result.Add(current);
                }
                else if (Regex.Match(line, "^@version").Success)
                {
                    string body = Regex.Replace(line, "^@version[ \t]*", "");
                    current = new CommentNode(CommentType.VERSION, body);
                    result.Add(current);
                }
                else if (Regex.Match(line, "^@see").Success)
                {
                    string body = Regex.Replace(line, "^@see[ \t]*", "");
                    current = new CommentNode(CommentType.SEE, body);
                    result.Add(current);
                }
                else if (Regex.Match(line, "^@description").Success)
                {
                    string body = Regex.Replace(line, "^@description[ \t]*", "");
                    if (current.Type != CommentType.DESCRIPTION)
                    {
                        current = new CommentNode(CommentType.DESCRIPTION, body);
                        result.Add(current);
                    }
                    else
                    {
                        if (current.Body.Length > 0)
                        {
                            current.Body += "\\n" + body;
                        }
                        else
                        {
                            current.Body = body;
                        }
                    }
                }
                else
                {
                    // previous type
                    if (current.Body.Length > 0)
                    {
                        current.Body += "\\n" + line;
                    }
                    else
                    {
                        current.Body = line;
                    }
                }
            }
            return(result);
        }
Пример #60
0
    /// <summary>
    /// csvファイル読み込み
    /// </summary>
    void csvLoader()
    {
        // csv
        TextAsset File;
        // csvのデータを格納List
        List <string[]> Data = new List <string[]>();

        // csvファイルをResourcesからロードする
        File = Resources.Load("StageFiles/No." +  number) as TextAsset;
        // StringReaderにすることでReadLine()やPeek()を使えるようにする
        System.IO.StringReader reader = new System.IO.StringReader(File.text);
        // Peekで文字列が読めなくなるまで実行する
        while (reader.Peek() != -1)
        {
            // 1行ずつ文字列を読み込む
            string line = reader.ReadLine();
            // 文字列をカンマで区切る
            Data.Add(line.Split(','));
        }
        // 要素数
        int length = int.Parse(Data[0][1]);
        // 列
        var    Row  = 0;  
        string path = "";
        // SpriteRenderer参照
        SpriteRenderer spriteRenderer = null;

        for (int line = 0; line <= length; line++)
        {
            // ArrowBlockがある場合
            if (Data[line][Row] == "ArrowBlock")
            {
                path = "Textures/stage/ArrowBlock";
                // 子オブジェクト(ArrowBlock)のSpriteRenderer参照
                spriteRenderer = transform.Find("ArrowBlock").GetComponent <SpriteRenderer>();
            }
            // CannotBlockがある場合
            else if (Data[line][Row] == "CannotBlock")
            {
                path = "Textures/stage/CannotBlock";
                // 子オブジェクト(CannotBlock)のSpriteRenderer参照
                spriteRenderer = transform.Find("CannotBlock").GetComponent <SpriteRenderer>();
            }
            // FixedBlockがある場合
            else if (Data[line][Row] == "FixedBlock")
            {
                path = "Textures/stage/FixedBlock";
                // 子オブジェクト(FixedBlock)のSpriteRenderer参照
                spriteRenderer = transform.Find("FixedBlock ").GetComponent <SpriteRenderer>();
            }
            // どのギミックにも該当しない場合
            else
            {
                continue;
            }
            // すでにspriteが設定されていたら2重にspriteを読み込まない制御
            if (spriteRenderer.sprite == null)
            {
                // Resourcesからspriteを読み込む
                var sprite = Resources.Load <Sprite>(path);
                // sprite設定
                spriteRenderer.sprite = sprite;
            }
        }
    }