Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
can someone please suggest a method wherein i can separate uppercase characters and lowercase characters in a string
input : "heLLoWorLd"
output : "heoordLLWL"
I have prepare one program for you to doing the same:
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
static void Main()
{
// Input string.
string mixedCase = "heLLoWorLd";
// Call ToLower instance method, which returns a new copy.
string lower = "";
string uper = "";
for (int i = 0; i < mixedCase.Length; i++)
{
if (char.IsLower(mixedCase[i]))
lower = lower + mixedCase[i];
else
uper = uper + mixedCase[i];
}
// Display results.
Console.WriteLine("{0}{1}",
lower,
uper);
}
}
OUTPUT:
heoordLLWL
This code will definitely helpful to you.Thank you!
You can make use of few extension methods like the following:
string strInput="heLLoWorLd";
string outputStr =String.Join("",strInput.GroupBy(x=>Char.IsLower(x))
.SelectMany(y=>y.ToList()));
You can try a working example here
Why not just a simple OrderBy? Imo GroupBy and SelectMany is a bit cracking a nut with a sledgehammer
string input = "heLLoWorLd";
string output = string.Concat(input.OrderBy(char.IsUpper)); // heoordLLWL
Try this:
string input = "heLLoWorLd";
string output = string.Empty;
output = String.Concat(input.Where(c => Char.IsLower(c))) + String.Concat(input.Where(c => Char.IsUpper(c))) ;
Another way,
string str = "WeLcoMe";
string _upper = string.Empty, _lower = string.Empty;
foreach (var s in str)
{
if (char.IsUpper(s))
_upper += s;
else
_lower += s;
}
str = _upper + _lower;
Output will be
WLMecoe
string input = "heLLoWorLd";
StringBuilder builder = new StringBuilder();
StringBuilder upp = new StringBuilder();
StringBuilder low = new StringBuilder();
foreach (char c in input)
{
if (Char.IsLower(c))
{
low.Append(c);
}
else
{
if (Char.IsUpper(c))
{
upp.Append(c);
}
}
}
string output = low.ToString() + upp.ToString();
var input = "heLLoWorLd";
var output = string.Concat(input.GroupBy(char.IsLower).SelectMany(c => c.ToList()));
Related
This question already has an answer here:
File.AppendText attempting to write to wrong location
(1 answer)
Closed 3 years ago.
I'm trying to edit a conf file by using line.Replace and write.WriteLine.
Debugging through the code, the line successfully changes.
Original string:
Changed string:
Somehow after the writer.WriteLine, the text still does not change. Below is my full code:
public void ChangeFileContent()
{
string textLoc = installPath + "\\DB\\influxdb-1.7.7-1\\influxdb.conf";
string[] arr = File.ReadAllLines(textLoc);
for (int i = 0; i < arr.Length; i++)
{
var writer = new StreamWriter(Path.GetFileName(textLoc));
string line = arr[i];
string output = line;
if (line.Contains("influxdb-1.7.7-1") == true)
{
output = line.Replace("D:", "C:");
}
writer.WriteLine(output);
writer.Close();
}
}
You could build all content and write it with File.WriteAllText or File.WriteAllLines.
Something like the following.
string textLoc = installPath + "\\DB\\influxdb-1.7.7-1\\influxdb.conf";
var lines = File.ReadAllLines(textLoc);
var newLines = lines.Select(line =>
line.Contains("influxdb-1.7.7-1")
? output = line.Replace("D:", "C:")
: line);
File.WriteAllLines(textLoc,newLines);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to read the File by Splitting each Row by removing whitespace through regex.split in c# but my code isn't working properly need help. Thanks in Advance.
text="";
OpenFileDialog open = new OpenFileDialog();
if (open.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Stream filestream = open.OpenFile();
if (filestream != null)
{
string filename = open.FileName;
text = File.ReadAllText(filename);
}
string code = textBox1.Text;
columncounter = code.Length;
string[] arrays = Regex.Split(code, #"\s+");
textBox1.Text = text;
}
If you are trying to write each row, without whitespace, to your TextBox, this should work:
var result = new StringBuilder();
foreach (var line in File.ReadAllLines(filename))
{
result.AppendLine(Regex.Replace(line, #"\s", "")));
}
textBox1.Text = result.ToString();
For faster performance, use string.Replace:
var result = new StringBuilder();
foreach (var line in File.ReadAllLines(filename))
{
result.AppendLine(line
.Replace("\t", "")
.Replace("\n", "")
.Replace("\r", "")
.Replace(" ", ""));
}
textBox1.Text = result.ToString();
Just add textBox1.text = string.Concat(arrays). It will concatenate the strings from the splitted array.
or you could do something like text.Replace(" ", "")
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have txt file which contains number that I want to grab. This number has prefix which can be used to identify location inside file.
GeneratedNumber="120"
Number can be of any Int32 length value.
p.s. format of the file is .txt, one line contains more this key value pairs for example:
<Output Change="12.13" GeneratedNumber="120" Total="99.21" />
You can use the following code. Not very elegant or the best but tested and works fine.
string[] lines = File.ReadAllLines(Path.Combine(Application.StartupPath, "test.txt"));
foreach (string s in lines)
{
if (s.ToLowerInvariant().Contains("generatednumber"))
{
string temp = s.Substring(s.ToLowerInvariant().IndexOf("generatednumber"));
temp = temp.Substring(temp.IndexOf("\"") + 1);
temp = temp.Substring(0,temp.IndexOf("\""));
int yournumber;
if (int.TryParse(temp, out yournumber))
{
Console.WriteLine("Generated Number = ", yournumber);
}
}
}
I've only tested this as far as the xml side but this should work (You may wish to add error handling and the conversion to integers)
var values = new List<string>();
using(var sr = new StreamReader(fileName))
{
string line;
XmlDocument x = new XmlDocument();
while((line = sr.ReadLine()) != null)
{
x.LoadXml(line);
foreach(var node in x.GetElementsByTagName("Output"))
values.Add(node.Attributes["GeneratedNumber"].Value);
}
}
Tested using:
XmlDocument x = new XmlDocument();
x.LoadXml("<Output Change=\"12.13\" GeneratedNumber=\"120\" Total=\"99.21\" />");
Console.WriteLine(x.GetElementsByTagName("Output")[0]
.Attributes["GeneratedNumber"].Value);
Console.ReadLine();
you can use this code
// Read each line of the file into a string array. Each element
// of the array is one line of the file.
string[] lines = System.IO.File.ReadAllLines(#"C:\yourFile.txt");
foreach (string line in lines)
{
string sub = line.Substring(line.IndexOf("GeneratedNumber=") + 1);
int num = int.Parse(sub.IndexOf("\""));
// whatever you want to do with the integer
}
to read the text file lines and parse the lines after the "=" sign to integers.
depend on the look of the file you might use XmlDocument. please read about Xml here
string filePath = "your_file_path";
var match = System.Text.RegularExpressions.Regex.Match(
System.IO.File.ReadAllText(filePath),
#"GeneratedNumber=""(\d+)""",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
int num = match.Success ? int.Parse(match.Groups[1].Value) : 0;
Assuming there's only one instance of that number in the file or you want to grab only the first one even if there are multiple.
string[] lines = File.ReadAllLines("path to file");
Hashtable values = new Hashtable();
foreach (string line in lines)
{
if (line.Contains("=\""))
{
string[] split = line.Split('=');
values.Add(split[0], split[1].Replace("\"",""));
}
}
// GeneratedNumber is the value of GeneratedNumber in the file.
int GeneratedNumber = Int32.Parse(values["GeneratedNumber"].ToString());
This code should match your needs:
private static int GetNumber(string fileName)
{
string line;
string key = "GeneratedNumber=\"";
using (StreamReader file = new StreamReader(fileName))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(key))
{
int startIndex = line.IndexOf(key) + key.Length;
int endIndex = line.IndexOf("\"", startIndex);
return int.Parse(line.Substring(startIndex, endIndex - startIndex));
}
}
}
return 0;
}
Also you may be interested in these articles:
Using of StreamReader
String methods
Int32.Parse method
I have a string as in the following format:
"one,",2,3,"four " ","five"
I need output in the following format:
one,
2
3
four "
five
Can anyone help me to create Regex for the above?
You can do this without Regex. It's not clear to me, what you're trying to do though. I've adjusted the code for the updated question:
var text = "\"one\",2,3,\"four \"\",\"five\"";
var collection = text
.Split(',')
.Select(s =>
{
if (s.StartsWith("\"") && s.EndsWith("\""))
{
s = s.Substring(1, s.Length - 2);
}
return s;
})
.ToList();
foreach (var item in collection)
{
Console.WriteLine(item);
}
I've added another sample for you, which uses a CSV reader. I've installed the "CsvHelper" package from NuGet:
const string text = "\"one,\",2,3,\"four \"\"\",\"five\"";
using (var textReader = new StringReader(text))
using (var reader = new CsvReader(textReader))
{
reader.Configuration.Delimiter = ',';
reader.Configuration.AllowComments = false;
reader.Configuration.HasHeaderRecord = false;
if (reader.Read())
{
foreach (var item in reader.CurrentRecord)
{
Console.WriteLine(item);
}
}
}
string newString = Regex.Replace(oldString, #'[^",]', ' ');
I hope the regular expression is good, but I just want you you to see the idea.
EDIT:
string newString = Regex.Replace(oldString, #'[^",]', '\n');
I have data coming from an nvarchar field of the SQL server database via EF3.5. This string is used to create a Filename and need to remove invalid characters and tried following options but none of them works. Please suggest why this is such an understandable mystery? Am I doing anything wrong?
I went though almost all of the related questions on this site.. and now posting a consolidated question from all the suggestions/answers from other similar questions.
UPD: The Issue was unrelated..All of these options do work. So posting it to community wiki.
public static string CleanFileName1(string filename)
{
string file = filename;
file = string.Concat(file.Split(System.IO.Path.GetInvalidFileNameChars(), StringSplitOptions.RemoveEmptyEntries));
if (file.Length > 250)
{
file = file.Substring(0, 250);
}
return file;
}
public static string CleanFileName2(string filename)
{
var builder = new StringBuilder();
var invalid = System.IO.Path.GetInvalidFileNameChars();
foreach (var cur in filename)
{
if (!invalid.Contains(cur))
{
builder.Append(cur);
}
}
return builder.ToString();
}
public static string CleanFileName3(string filename)
{
string regexSearch = string.Format("{0}{1}",
new string(System.IO.Path.GetInvalidFileNameChars()),
new string(System.IO.Path.GetInvalidPathChars()));
Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
string file = r.Replace(filename, "");
return file;
}
public static string CleanFileName4(string filename)
{
return new String(filename.Except(System.IO.Path.GetInvalidFileNameChars()).ToArray());
}
public static string CleanFileName5(string filename)
{
string file = filename;
foreach (char c in System.IO.Path.GetInvalidFileNameChars())
{
file = file.Replace(c, '_');
}
return file;
}
Here is a function I use in a static common class:
public static string RemoveInvalidFilePathCharacters(string filename, string replaceChar)
{
string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
return r.Replace(filename, replaceChar);
}
Try this
filename = Regex.Replace(filename, "[\/?:*""><|]+", "", RegexOptions.Compiled)
no invalid chars returned by System.IO.Path.GetInvalidFileNameChars() being removed. – Bhuvan 5 mins ago
The first method you posted works OK for the characters in Path.GetInvalidFileNameChars(), here it is at work:
static void Main(string[] args)
{
string input = "abc<def>ghi\\1234/5678|?9:*0";
string output = CleanFileName1(input);
Console.WriteLine(output); // this prints: abcdefghi1234567890
Console.Read();
}
I suppose though that your problem is with some language-specific special characters. You can try to troubleshoot this problem by printing out the ASCII codes of the characters in your string:
string stringFromDatabase = "/5678|?9:*0"; // here you get it from the database
foreach (char c in stringFromDatabase.ToCharArray())
Console.WriteLine((int)c);
and consulting the ASCII table: http://www.asciitable.com/
I again suspect that you'll see characters with codes larger than 128, and you should exclude those from your string.