I have a string called fileNameArrayEdited which contains "\\windows".The below if statement is not running.
Thinking the problem is else where as people have given me code that should work will be back once I found the problem... thanks!
if (fileNameArrayEdited.StartsWith("\\"))
{
specifiedDirCount = specifiedDirCount + 1;
}
// Put all file names in root directory into array.
string[] fileNameArray = Directory.GetFiles(#specifiedDir);
int specifiedDirCount = specifiedDir.Count();
string fileNameArrayEdited = specifiedDir.Remove(0, specifiedDirCount);
Console.WriteLine(specifiedDir.Remove(0, specifiedDirCount));
if (fileNameArrayEdited.StartsWith(#"\\"))
{
specifiedDirCount = specifiedDirCount + 1;
Console.ReadLine();
Use '#' at the beginning of your string if you are searching for exactly two slash
if (fileNameArrayEdited.StartsWith(#"\\"))
{
specifiedDirCount = specifiedDirCount + 1;
}
They are called verbatim strings and they are ignoring escape characters.For better explanation you can take a look at here: http://msdn.microsoft.com/en-us/library/362314fe.aspx
But I suspect in here your one slash is escape character
"\\windows"
So you must search for one slash like this:
if (fileNameArrayEdited.StartsWith(#"\"))
{
specifiedDirCount = specifiedDirCount + 1;
}
When we write
string s1 = "\\" ;
// actual value stored in s1 is "\"
string s2 = #"\\" ;
// actual value stored in s2 is "\\"
The second type of string(s) are called "verbatim" strings.
Related
I am using c# and in code from appsettings.json I take strings and convert them if special chars exists. this is my code
int? a = applicationRequestViewModel.GetApplicantIndex();
int? g = applicationRequestViewModel.GetGurantorIndex();
foreach (var keys in _options.Value.RegisterParamKeys)
{
string value = keys.Split(";")[0];
string name = keys.Split(";")[1];
string key = value.Split(":")[typeOfApplicant];
key = Regex.Replace(key, #"[^\[a\]]", "[" + a + "]");
key = Regex.Replace(key, #"[^\[g\]]", "[" + g + "]");
var registrationProperty = new RegistrationProperty() { };
registrationProperty.Name = name;
registrationProperty.Value = (string)rss.SelectToken(key);
listOfRegistrationProperty.Add(registrationProperty);
}
from appsettings.json I took below strings
"RegisterBatchParams": [
"applicationInfo.applicationNumber:applicationInfo.applicationNumber:applicationInfo.applicationNumber:applicationInfo.applicationNumber;applicationNumber",
"applicationInfo.applicantType:applicationInfo.applicantType:applicationInfo.applicantType:applicationInfo.applicantType;applicantType",
"applicationInfo.customerSegment:applicationInfo.customerSegment:applicationInfo.customerSegment:applicationInfo.customerSegment;customerSegment",
"applicationInfo.applicationStatusLocalText:applicationInfo.applicationStatusLocalText:applicationInfo.applicationStatusLocalText:applicationInfo.applicationStatusLocalText;applicationStatus",
"applicationRequestViewModel.applicants[a].businessPartner.person.firstName:applicationRequestViewModel.applicants[a].businessPartner.person.firstName:applicationRequestViewModel.applicants[a].businessPartner.person.firstName:applicationRequestViewModel.applicants[a].businessPartner.person.firstName;customerName"
],
for the last string I want to change "applicants[a]" to with index number but it doesn't convert as expected how can I convert correctly?
As expected result
applicationRequestViewModel.applicants[0].businessPartner.person.firstName
but given result
a[0][0][0][0][0]a[0][0][0][0][0][0][0][0][0]a[0][0][0][0][0]a[0][0][0][0][0][0][0][0][0][0]
Instead of #"[^\[a\]]" use #"\[a\]".
But you don't even need regex for this. Simple string.Replace will do the job just as well.
Or, you can try this regex and replace only char inside of parentheses.
[a](?=[]])
I'm making a basic program, and when it comes to saving data I'm trying to put it into a .txt - which is working just fine. Problem is, I can't save the seconds/hours in addition to the date, so my solution was to just get the date and then put 1, 2, 3 respectively on most recent files. The code I made was:
static string FileName()
{
string fileName = "";
char last = ' ';
int lastDigit = 0;
string lastDigitString = "";
string directory = Directory.GetCurrentDirectory();
if (File.Exists(DateTime.Now.Date.ToString("dd-MM-yy" + "1") + ".txt"))
{
fileName = Path.GetFileNameWithoutExtension(newFileName + ".txt");
last = fileName[fileName.Length - 1];
lastDigit = int.Parse(last.ToString());
lastDigit = lastDigit + 1;
lastDigitString = lastDigit.ToString();
newFileName = fileName + lastDigitString;
}
else
{
newFileName = DateTime.Now.Date.ToString("dd-MM-yy" + "1");
}
return fileName;
}
with newFileName being defined as a global variable at the top.
public static string newFileName = DateTime.Now.Date.ToString("dd-MM-yy" + "1");
I've been messing around with some things might be out of place. My solution was to get the filename and then take off the .txt - which would then leave me with just the name where I get the last digit of the name and then increase it by one, then add it to the end of a new file name. It goes 'FileName1' then 'FileName12' which is what I hoped to get, but once there it just keeps adding to 'FileName12' which is obviously from the appending set to true, but I hoped for a 'FileName123'.
Is there a requirement not to use the Hour/Minute/Second for your file name?
You are using DateTime.Now.Date.ToString(..), which will strip out the hour/minute/second data. You can use DateTime.Now.ToString(..) to reserve the sub-day data.
You'll need to provide your own format string to generate a file-name-friendly output.
This is because time has colon : and it is not supported as windows file
string s = "apple]","[banana...." ;
I need to remove ( "]","[ ) and replace with "," from above string so that the output looks like below:
s = "apple,banana...."
s = s.Replace(#"\]","[\", ","); //something like this?
You need to escape the quotation marks in the string. You have tried to escape something, but \ isn't used to escape characters in a # delimited string.
In a # delimited string you use "" to escape ":
s = s.Replace(#"]"",""[", ",");
In a regular string you use \" to escape ":
s = s.Replace("]\",\"[", ",");
I assume it is a string[]?
I propose something like this:
string[] s = {"[apple]","[banana]","[orange]"} ;
string new_s = "";
foreach (string ss in s)
{
new_s += ss.Replace("[", "").Replace("]", ",");
}
//handle extra "," at end of string
new_s = new_s.Remove(new_s.Length-1);
Edit: Disregard, I misunderstood what you were trying to accomplish due to syntactical errors in your string definition.
string s = "apple]","[banana...." ;
should be:
string s = "apple]\",\"[banana....";
I have some string and I would like to replace the last .something with a new string. As example:
string replace = ".new";
blabla.test.bla.text.jpeg => blabla.test.bla.text.new
testfile_this.00001...csv => testfile_this.00001...new
So it doesn't matter how many ..... there are, I'd like to change only the last one and the string what after the last . is coming.
I saw in C# there is Path.ChangeExtension but its only working in a combination with a File - Is there no way to use this with a string only? Do I really need regex?
string replace = ".new";
string p = "blabla.test.bla.text.jpeg";
Console.WriteLine(Path.GetFileNameWithoutExtension(p) + replace);
Output:
blabla.test.bla.text.new
ChangeExtension should work as advertised;
string replace = ".new";
string file = "testfile_this.00001...csv";
file = Path.ChangeExtension(file, replace);
>> testfile_this.00001...new
You can use string.LastIndexOf('.');
string replace = ".new";
string test = "blabla.test.bla.text.jpeg";
int pos = test.LastIndexOf('.');
if(pos >= 0)
string newString = test.Substring(0, pos-1) + replace;
of course some checking is required to be sure that LastIndexOf finds the final point.
However, seeing the other answers, let me say that, while Path.ChangeExtension works, it doesn't feel right to me to use a method from a operating system dependent file handling class to manipulate a string. (Of course, if this string is really a filename, then my objection is invalid)
string s = "blabla.test.bla.text.jpeg";
s = s.Substring(0, s.LastIndexOf(".")) + replace;
No you don't need regular expressions for this. Just .LastIndexOf and .Substring will suffice.
string replace = ".new";
string input = "blabla.bla.test.jpg";
string output = input.Substring(0, input.LastIndexOf('.')) + replace;
// output = "blabla.bla.test.new"
Please use this function.
public string ReplaceStirng(string originalSting, string replacedString)
{
try
{
List<string> subString = originalSting.Split('.').ToList();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < subString.Count - 1; i++)
{
stringBuilder.Append(subString[i]);
}
stringBuilder.Append(replacedString);
return stringBuilder.ToString();
}
catch (Exception ex)
{
if (log.IsErrorEnabled)
log.Error("[" + System.DateTime.Now.ToString() + "] " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + " :: " + System.Reflection.MethodBase.GetCurrentMethod().Name + " :: ", ex);
throw;
}
}
How to remove whitespaces between characters in c#?
Trim() can be used to remove the empty spaces at the beginning of the string as well as at the end. For example " C Sharp ".Trim() results "C Sharp".
But how to make the string into CSharp? We can remove the space using a for or a for each loop along with a temporary variable. But is there any built in method in C#(.Net framework 3.5) to do this like Trim()?
You could use String.Replace method
string str = "C Sharp";
str = str.Replace(" ", "");
or if you want to remove all whitespace characters (space, tabs, line breaks...)
string str = "C Sharp";
str = Regex.Replace(str, #"\s", "");
If you want to keep one space between every word. You can do it this way as well:
string.Join(" ", inputText.Split(new char[0], StringSplitOptions.RemoveEmptyEntries).ToList().Select(x => x.Trim()));
Use String.Replace to replace all white space with nothing.
eg
string newString = myString.Replace(" ", "");
if you want to remove all spaces in one word:
input.Trim().Replace(" ","")
And If you want to remove extra spaces in the sentence, you should use below:
input.Trim().Replace(" +","")
the regex " +", would check if there is one ore more following space characters in the text and replace them with one space.
If you want to keep one space between every word. this should do it..
public static string TrimSpacesBetweenString(string s)
{
var mystring =s.RemoveTandNs().Split(new string[] {" "}, StringSplitOptions.None);
string result = string.Empty;
foreach (var mstr in mystring)
{
var ss = mstr.Trim();
if (!string.IsNullOrEmpty(ss))
{
result = result + ss+" ";
}
}
return result.Trim();
}
it will remove the string in between the string
so if the input is
var s ="c sharp";
result will be "c sharp";
//Remove spaces from a string just using substring method and a for loop
static void Main(string[] args)
{
string businessName;
string newBusinessName = "";
int i;
Write("Enter a business name >>> ");
businessName = ReadLine();
for(i = 0; i < businessName.Length; i++)
{
if (businessName.Substring(i, 1) != " ")
{
newBusinessName += businessName.Substring(i, 1);
}
}
WriteLine("A cool web site name could be www.{0}.com", newBusinessName);
}
var str=" c sharp "; str = str.Trim();
str = Regex.Replace(str, #"\s+", " "); ///"c sharp"
string myString = "C Sharp".Replace(" ", "");
I found this method great for doing things like building a class that utilizes a calculated property to take lets say a "productName" and stripping the whitespace out to create a URL that will equal an image that uses the productname with no spaces. For instance:
namespace XXX.Models
{
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public string ProductImage
{
get { return ProductName.Replace(" ", string.Empty) + ".jpg"; }
}
}
}
So in this answer I have used a very similar method as w69rdy, but used it in an example, plus I used string.Empty instead of "". And although after .Net 2.0 there is no difference, I find it much easier to read and understand for others who might need to read my code. I also prefer this because I sometimes get lost in all the quotes I might have in a code block.