P
P
pw0ned2018-09-07 01:08:07
C++ / C#
pw0ned, 2018-09-07 01:08:07

Replace last character of a string with big character in C#, how?

Good evening, I'm practicing with files.
It is necessary to replace the last letter of the line in all lines with a capital one, but so far it has only been possible to delete it, and for some reason it only deletes from the last line in the file (why so?) ...
Please push the right idea, how to implement this?

string path = @"1.txt";
            using (FileStream fstream = File.OpenRead(path))
            {
                byte[] array = new byte[fstream.Length];
                fstream.Read(array, 0, array.Length);
                string textFromFile = System.Text.Encoding.Default.GetString(array);
                string y = textFromFile.Remove(textFromFile.Length - 1);
                Console.WriteLine(y);
                Console.ReadLine();

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
eRKa, 2018-09-07
@kttotto

On the knee, but something like this

var lines = File.ReadLines(path);
foreach(var line in lines)
{
  var index = line.Length - 1
  line[index] = line[index].ToUpper()
}

var text = string.Join(lines);
File.WriteAllText(path, text);

#
#, 2018-09-07
@mindtester

On the knee
doesn’t work .. there’s a lot to do with it ..
for example, here’s what works (with comments):
using System;
using System.IO;
using System.Linq;

namespace lastChar
{
    class Program
    {
        static void Main(string[] args)
        {
            var lines = File.ReadAllLines(@"C:\Windows\System32\drivers\etc\hosts"); // для примера
            for (var i=0; i < lines.Count(); i++) // в итераторе foreach элементы readonly.. типа функциональный стиль
            {
                if (!string.IsNullOrWhiteSpace(lines[i])) // а то на пустых строках эксепшен будем ловить
                {
                    // строка, блин, штука то то же не изменяемая.. вот засада
                    var ch = lines[i].ToCharArray();
                    var idx = ch.Length - 1;
                    ch[idx] = Char.ToUpper(ch[idx]);
                    lines[i] = new string(ch);
                }
                Console.WriteLine(lines[i]);
            }
            Console.ReadKey();
            //сохраняйте как хотите
            //... и да - точки (решетки) в апкейсе остаются точками. только буквы можно апкейсить
        }
    }
}

upd works - thanks to Meloman19 for the hint in the comments. almost perfect now

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question