Why doesn't this work ?
string myString = "test";
int i = myString.Length; // i = 4
myString.PadLeft(5, '_'); // "myString" is should be equal to "_test", but it still "test"
i = myString.Length; // i = 4 (should be 5)
Most string methods don't change string itself, but return new string, so use it like this:
myString = myString.PadLeft(5, '_');
EDIT: Ahh yes, all methods. I thought about methods that don't return string and somehow ended with not entirely true sentence.
Related
So what I am trying to do is as follows :
example of a string is A4PC
I am trying to replace for example any occurance of "A" with "[A4]" so I would get and similar any occurance of "4" with "[A4]"
"[A4][A4]PC"
I tried doing a normal Replace on the string but found out I got
"[A[A4]]PC"
string badWordAllVariants =
restriction.Value.Replace("A", "[A4]").Replace("4", "[A4]")
since I have two A's in a row causing an issue.
So I was thinking it would be better rather than the replace on the string I need to do it on a character per character basis and then build up a string again.
Is there anyway in Linq or so to do something like this ?
You don't need any LINQ here - String.Replace works just fine:
string input = "AAPC";
string result = input.Replace("A", "[A4]"); // "[A4][A4]PC"
UPDATE: For your updated requirements I suggest to use regular expression replace
string input = "A4PC";
var result = Regex.Replace(input, "A|4", "[A4]"); // "[A4][A4]PC"
This works well for me:
string x = "AAPC";
string replace = x.Replace("A", "[A4]");
EDIT:
Based on the updated question, the issue is the second replacement. In order to replace multiple strings you will want to do this sequentially:
var original = "AAPC";
// add arbitrary room to allow for more new characters
StringBuilder resultString = new StringBuilder(original.Length + 10);
foreach (char currentChar in original.ToCharArray())
{
if (currentChar == 'A') resultString.Append("[A4]");
else if (currentChar == '4') resultString.Append("[A4]");
else resultString.Append(currentChar);
}
string result = resultString.ToString();
You can run this routine with any replacements you want to make (in this case the letters 'A' and '4' and it should work. If you would want to replace strings the code would be similar in structure but you would need to "look ahead" and probably use a for loop. Hopefully this helps!
By the way - you want to use a string builder here and not strings because strings are static which means space gets allocated every time you loop. (Not good!)
I think this should do the trick
string str = "AA4PC";
string result = Regex.Replace(str, #"(?<Before>[^A4]?)(?<Value>A|4)(?<After>[^A4]?)", (m) =>
{
string before = m.Groups["Before"].Value;
string after = m.Groups["After"].Value;
string value = m.Groups["Value"].Value;
if (before != "[" || after != "]")
{
return "[A4]";
}
return m.ToString();
});
It is going to replace A and 4 that hasn't been replaced yet for [A4].
How to solve substring issue. I have tried to code correctly but not working for me.
The file name is bad_filename.xml or good_filename.xml
what i want is to use substring to result "bad" or "good" where _filename.xml should be removed. how to do this?
From: bad_filename.xml or good_filename.xml
to: bad or good
Try this
string s = "bad_filename.xml";
string sub = s.Substring(0, s.IndexOf("_"));
string sub2 = string.Concat((s.TakeWhile(x => x != '_')));
string sub3 = s.Split('_')[0];
I've given three ways pick any one of your choice
Note: Way (1) will throw exception when string doesn't contain _ you need to check index > -1
Try this, as I have mention in Question comment.
var result = filename.Split('_')[0];
var result = filename.Split('_')[0];
Use the Path class to get the file name and string.Split to get the first part:
string fileNameWOE = Path.GetFileNameWithoutExtension("bad_filename.xml");
string firstPart = fileNameWOE.Split('_')[0];
try this
string input = "bad_filename.xml"
string sub = input.Substring(0, input.IndexOf("_"));
Console.WriteLine("Substring: {0}", sub);
You can use this code for substring.
string a="bad_filename.xml ";
int index=a.IndexOf('_');
if (index != -1)
{
string filename = a.Substring(0,index);
}
output is bad
do it like this :
string[] strArr = stringFileName.Split('_');
string[] strArr = bad_filename.xml.Split('_');
strArr[0] is "bad"
and
string[] strArr = good_filename.xml.Split('_');
strArr[0] is "good"
I have a name which is made of a prefix a type and name , i want to retrieve the name part.
Prefix always remains same but Type can change.
I have the following code to get the name part:
string prefix = "Prefix-";
string str =prefix + "Type-hello-j---.xml";
str = Path.GetFileNameWithoutExtension(str);
str = str.Substring(prefix.Length);
str = str.Substring(str.IndexOf('-') + 1);
In the above example the name part is: hello-j---
Is there any efficient/better way to do the same in C# ?
You can use an overload of string.Split() that lets you specify the number of parts:
string fileName = "Prefix-Type-hello-j---.xml";
string withoutExtension = Path.GetFileNameWithoutExtension(str);
var parts = str.Split(new[]{'-'}, 3);
string name = parts[2];
If this is always the structure of your string, this would work :
string name = str.Split(new[]{'-'})[2];
I'm assuming you only want "hello". If you want the rest of the name you could use the overloaded method as #KingCronus suggested :
string name = str.Split(new[]{'-'}, 3)[2];
You can also create an extension function that works like String.IndexOf but that gets the position of the nth occurrence of the specified character:
public static int IndexOfWithCount(this string input, char character, int occurenceNumber)
{
int count = 0;
for (int numCaracter = 0; numCaracter < input.Length; numCaracter++)
if (input[numCaracter] == character)
{
count++;
if (count == occurenceNumber)
return numCaracter;
}
return -1;
}
To use it:
string nameWithoutExt = Path.GetFileNameWithoutExtension(str);
string result = nameWithoutExt.Substring(nameWithoutExt.IndexOfWithCount('-', 2) + 1);
It depends how you define efficient but if lines of code fits your defintion how about:
var str = "prefix-Type-hello-j---.xml";
var name = Regex.Match(str, #"(.+?-)(.+?-)(?<name>.+)\.").Groups["name"].Value;
The first two capturing groups consume the prefix and the the type then the namedgroup consumes the name until the extension starts.
This code assumes there is always a match, if there is not it will throw a nullreference exception.
See Regex.Match
Why the code below doesnt work ?
string Tmp_actionFilepath = #"Temp\myaction.php";
// change the id and the secret code in the php file
File.Copy(#"Temp\settings.php", Tmp_actionFilepath, true);
string ActionFileContent = File.ReadAllText(Tmp_actionFilepath);
string unique_user_id = textBox5.Text.Trim();
string secret_code = textBox1.Text.Trim();
ActionFileContent.Replace("UNIQUE_USER_ID", unique_user_id);
ActionFileContent.Replace("SECRET_CODE", secret_code);
File.WriteAllText(Tmp_actionFilepath, ActionFileContent);
Here is the content of setting.php
<?php
session_start();
$_SESSION["postedData"] = $_POST;
/////////////////////////////////////////////////////////
$_SESSION["uid"] = "UNIQUE_USER_ID";
$_SESSION["secret"] = "SECRET_CODE";
/////////////////////////////////////////////////////////
function findThis($get){
$d = '';
for($i = 0; $i < 30; $i++){
if(file_exists($d.$get)){
return $d;
}else{
$d.="../";
}
}
}
$rootDir = findThis("root.cmf");
require_once($rootDir."validate_insert.php");
What is wrong with the code above ? After compiling the code in c#, i noticed the file myaction.php is created, but the values : UNIQUE_USER_ID and SECRET_CODE doesn't change, I tried also to copy/paste these values to make sure they are same. But the code always doesn't work
String.Replace returns a new string as strings are immutable. It does not replace the string you are calling it on.
You should replace:
ActionFileContent.Replace("UNIQUE_USER_ID", unique_user_id);
ActionFileContent.Replace("SECRET_CODE", secret_code);
with:
ActionFileContent = ActionFileContent.Replace("UNIQUE_USER_ID", unique_user_id);
ActionFileContent = ActionFileContent.Replace("SECRET_CODE", secret_code);
On top of that you should really change your variable names so they follow the regular C# naming conventions (i.e. use actionFileContent instead of ActionFileContent).
you have to set the result of the replace string method on a string.
string Tmp_actionFilepath = #"Temp\myaction.php";
// change the id and the secret code in the php file
File.Copy(#"Temp\settings.php", Tmp_actionFilepath, true);
string actionFileContent = File.ReadAllText(Tmp_actionFilepath);
string unique_user_id = textBox5.Text.Trim();
string secret_code = textBox1.Text.Trim();
// set the result of the Replace method on the string.
actionFileContent = ActionFileContent.Replace("UNIQUE_USER_ID", unique_user_id)
.Replace("SECRET_CODE", secret_code);
File.WriteAllText(Tmp_actionFilepath, actionFileContent);
I have a string "http://site1/site2/site3". I would like to get the value of "site2" out of the string. What is the best algorythm in C# to get the value. (no regex because it needs to be fast). I also need to make sure it doesn't throw any errors (just returns null).
I am thinking something like this:
currentURL = currentURL.ToLower().Replace("http://", "");
int idx1 = currentURL.IndexOf("/");
int idx2 = currentURL.IndexOf("/", idx1);
string secondlevelSite = currentURL.Substring(idx1, idx2 - idx1);
Assuming currentURL is a string
string result = new Uri(currentURL).Segments[1]
result = result.Substring(0, result.Length - 1);
Substring is needed because Segments[1] returns "site2/" instead of "site2"
Your example should be fast enough. If we really want to be nitpicky, then don't do the initial replace, because that will be at least an O(n) operation. Do a
int idx1 = currentURL.IndexOf("/", 8 /* or something */);
instead.
Thus you have two O(n) index look-ups that you optimized in the best possible way, and two O(1) operations with maybe a memcopy in the .NET's Substring(...) implementation... you can't go much faster with managed code.
currentURL = currentURL.ToLower().Replace("http://", "");
var arrayOfString = String.spilt(currentUrl.spit('/');
My assumption is you only need the second level. if there's no second level then it'll just return empty value.
string secondLevel = string.Empty;
try
{
string currentURL = "http://stackoverflow.com/questionsdgsgfgsgsfgdsggsg/3358184/parse-string-value-from-a-url-using-c".Replace("http://", string.Empty);
int secondLevelStartIndex = currentURL.IndexOf("/", currentURL.IndexOf("/", 0)) + 1;
secondLevel = currentURL.Substring(secondLevelStartIndex, (currentURL.IndexOf("/", secondLevelStartIndex) - secondLevelStartIndex));
}
catch
{
secondLevel = string.Empty;
}