I have many strings which have multiple spaces and one forward slash like this:
string a="xxxxxx xxx xxxxxxxx xxxxxx aaa/xxxxxxxxxxxxxxx";
or
string b="xxxx xxx xxxxxx bbbbb/xxxxxxx xxx";
or
string c="xx xx 12345/x xx"
What I need to do is to replace the substring "aaa" or "bbbbb" or "12345" (Please note that the substrings are just examples, they can be anything) with the new string I want.
The feature for the substring "aaa" or "bbbbb" or "12345" or anything is that the substring is right before the only one forward slash and right after the space in front of and closest to this slash.
How do I locate this substring so that I can replace it with the new substring I want? Thanks.
Well, well well
Take your universal method:
public string Replacement(string input, string replacement)
{
string[] words = input.Split(' ');
string result = string.Empty;
for (int i = 0; i < words.Length; i++)
{
if(words[i].Contains('/'))
{
int barIndex = Reverse(words[i]).LastIndexOf('/') + 1;
int removeLenght = words[i].Substring(barIndex).Length;
words[i] = Reverse(words[i]);
words[i] = words[i].Remove(barIndex, removeLenght);
words[i] = words[i].Insert(barIndex, Reverse(replacement));
string ToReverse = words[i];
words[i] = Reverse(ToReverse);
break;
}
}
for(int i = 0; i < words.Length; i++)
{
result += words[i] + " ";
}
result = result.Remove(result.Length - 1);
return result;
}
public string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
In reponse to >> I need a universal method to replace any stuff between the slash and the space closest to it
although a proposed answer is selected. I still decide to answer my own question.
string substr=""//any string I want
string a=OldString.split('/');//split by '/'
string b=a[0].Substring(0,a[0].LastIndexOf(' '));//get the substring before the last space
string NewString= b+ substr + a[1];//the substring between the space and the '/' is now replaced by substr
You should consider using a regex
Expression could be something like this "([^/]+)\\s(\\w+)/(.+)"
Regex.Replace (yourString, "([^/]+)\\s(\\w+)/(.+)", "$1 replacement/$3")
Regex.Replace
Use string.Replace("", "");
string a="xxxxxx xxx xxxxxxxx xxxxxx aaa/xxxxxxxxxxxxxxx";
string b="xxxx xxx xxxxxx bbbbb/xxxxxxx xxx";
string resultA = a.Replace("aaa", "Your replacement");
string resultB = b.Replace("bbbbb", "Your replacement");
Related
I want to replace all Special Characters which can't be parse in URL including space, double space or any big space with '-' using C#.
I don't want to use any Parse Method like System.Web.HttpUtility.UrlEncode.
How to do this ? I want to include any number of space between two words with just one '-'.
For example, if string is Hello# , how are you?
Then, Result should be, Hello-how-are-you, no '-' if last index is any special character or space.
string str = "Hello# , how are you?";
string newstr = "";
//Checks for last character is special charact
var regexItem = new Regex("[^a-zA-Z0-9_.]+");
//remove last character if its special
if (regexItem.IsMatch(str[str.Length - 1].ToString()))
{
newstr = str.Remove(str.Length - 1);
}
string replacestr = Regex.Replace(newstr, "[^a-zA-Z0-9_]+", "-");
INPUT:
Hello# , how are you?
OUTPUT:
Hello-how-are-you
EDIT:
Wrap it inside a class
public static class StringCheck
{
public static string Checker()
{
string str = "Hello# , how are you?";
string newstr = null;
var regexItem = new Regex("[^a-zA-Z0-9_.]+");
if (regexItem.IsMatch(str[str.Length - 1].ToString()))
{
newstr = str.Remove(str.Length - 1);
}
string replacestr = Regex.Replace(newstr, "[^a-zA-Z0-9_]+", "-");
return replacestr;
}
}
and call like this,
string Result = StringCheck.Checker();
string[] arr1 = new string[] { " ", "#", "&" };
newString = oldString;
foreach repl in arr1
{
newString= newString.Replace(repl, "-");
}
Of course you can add into an array all of your spec characters, and looping trough that, not only the " ".
More about the replace method at the following link
You need two steps to remove last special character and to replace all the remaining one or more special characters with _
public static void Main()
{
string str = "Hello# , how are you?";
string remove = Regex.Replace(str, #"[\W_]$", "");
string result = Regex.Replace(remove, #"[\W_]+", "-");
Console.WriteLine(result);
Console.ReadLine();
}
IDEONE
I want to trim a string after a special character..
Lets say the string is str="arjunmenon.uking". I want to get the characters after the . and ignore the rest. I.e the resultant string must be restr="uking".
How about:
string foo = str.EverythingAfter('.');
using:
public static string EverythingAfter(this string value, char c)
{
if(string.IsNullOrEmpty(value)) return value;
int idx = value.IndexOf(c);
return idx < 0 ? "" : value.Substring(idx + 1);
}
you can use like
string input = "arjunmenon.uking";
int index = input.LastIndexOf(".");
input = input.Substring(index+1, input.Split('.')[1].ToString().Length );
Use Split function
Try this
string[] restr = str.Split('.');
//restr[0] contains arjunmenon
//restr[1] contains uking
char special = '.';
var restr = str.Substring(str.IndexOf(special) + 1).Trim();
Try Regular Expression Language
using System.IO;
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "arjunmenon.uking";
string pattern = #"[a-zA-Z0-9].*\.([a-zA-Z0-9].*)";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine(match.Value);
if (match.Groups.Count > 1)
for (int ctr = 1; ctr < match.Groups.Count; ctr++)
Console.WriteLine(" Group {0}: {1}", ctr, match.Groups[ctr].Value);
}
}
}
Result:
arjunmenon.uking
Group 1: uking
Personally, I won't do the split and go for the index[1] in the resulting array, if you already know that your correct stuff is in index[1] in the splitted string, then why don't you just declare a constant with the value you wanted to "extract"?
After you make a Split, just get the last item in the array.
string separator = ".";
string text = "my.string.is.evil";
string[] parts = text.Split(separator);
string restr = parts[parts.length - 1];
The variable restr will be = "evil"
string str = "arjunmenon.uking";
string[] splitStr = str.Split('.');
string restr = splitStr[1];
Not like the methods that uses indexes, this one will allow you not to use the empty string verifications, and the presence of your special caracter, and will not raise exceptions when having empty strings or string that doesn't contain the special caracter:
string str = "arjunmenon.uking";
string restr = str.Split('.').Last();
You may find all the info you need here : http://msdn.microsoft.com/fr-fr/library/b873y76a(v=vs.110).aspx
cheers
I think the simplest way will be this:
string restr, str = "arjunmenon.uking";
restr = str.Substring(str.LastIndexOf('.') + 1);
I need to create a 10-character string. If the string has less than 10 characters i need to append blank spaces till complete the entire 10-character string. I do the following but I have no succes, the result string has only one blank space concateneted in the end:
public void MyMethod(string[] mystrings)
{
mystring[i].PadRight(10- mystrings[i].length)
// Here I need a 10 char string. For example:
// "1234567 "
}
Thank you.
You could use String.PadRight:
mystring = mystring.PadRight(10, ' ');
(You can omit the second parameter, as in your case, when you use spaces).
Note however, that if mystring is already longer than 10 characters, it will remain longer. It is not clear from your question, if you need a string with exactly 10 characters length. If so, then do something like:
mystring = mystring.PadRight(10).Substring(0, 10);
You can use string.Format with a custom format string:
mystring = string.Format("{0,-10}", mystring);
You need to use the string.PadRight method:
string result = mystring.PadRight(10);
try this
string str = "cc";
int charstoinsert = 10 - str.Length;
for (int i = 0; i < charstoinsert; i++)
{
str += " ";
}
Try with following function
#region GetPaddedString
private string GetPaddedString(string strValue, int intLength)
{
string strReturn = string.Empty;
string _strEmptySpace = " ";
int _vinLength = strValue.Length;
if (_vinLength < intLength)
{
strReturn = strValue + _strEmptySpace.PadRight((intLength - _vinLength));
}
else
{
strReturn = strValue;
}
return strReturn;
}
#endregion
GetPaddedString("test", 10)
This should do the trick:
str.PadRight(10, ' ').Substring(0, 10)
try this
string mystring= "sd";
while (mystring.Length <= 10)
{
mystring+= " ";
}
I have a file name: kjrjh20111103-BATCH2242_20111113-091337.txt
I only need 091337, not the txt or the - how can I achieve that. It does not have to be 6 numbers it could be more or less but will always be after "-" and the last ones before ."doc" or ."txt"
You can either do this with a regex, or with simple string operations. For the latter:
int lastDash = text.LastIndexOf('-');
string afterDash = text.Substring(lastDash + 1);
int dot = afterDash.IndexOf('.');
string data = dot == -1 ? afterDash : afterDash.Substring(0, dot);
Personally I find this easier to understand and verify than a regular expression, but your mileage may vary.
String fileName = kjrjh20111103-BATCH2242_20111113-091337.txt;
String[] splitString = fileName.Split ( new char[] { '-', '.' } );
String Number = splitString[2];
Regex: .*-(?<num>[0-9]*). should do the job. num capture group contains your string.
The Regex would be:
string fileName = "kjrjh20111103-BATCH2242_20111113-091337.txt";
string fileMatch = Regex.Match(fileName, "(?<=-)\d+", RegexOptions.IgnoreCase).Value;
String fileName = "kjrjh20111103-BATCH2242_20111113-091337.txt";
var startIndex = fileName.LastIndexOf('-') + 1;
var length = fileName.LastIndexOf('.') - startIndex;
var output = fileName.Substring(startIndex, length);
How can the first letter in a text be set to capital?
Example:
it is a text. = It is a text.
public static string ToUpperFirstLetter(this string source)
{
if (string.IsNullOrEmpty(source))
return string.Empty;
// convert to char array of the string
char[] letters = source.ToCharArray();
// upper case the first char
letters[0] = char.ToUpper(letters[0]);
// return the array made of the new char array
return new string(letters);
}
It'll be something like this:
// precondition: before must not be an empty string
String after = before.Substring(0, 1).ToUpper() + before.Substring(1);
polygenelubricants' answer is fine for most cases, but you potentially need to think about cultural issues. Do you want this capitalized in a culture-invariant way, in the current culture, or a specific culture? It can make a big difference in Turkey, for example. So you may want to consider:
CultureInfo culture = ...;
text = char.ToUpper(text[0], culture) + text.Substring(1);
or if you prefer methods on String:
CultureInfo culture = ...;
text = text.Substring(0, 1).ToUpper(culture) + text.Substring(1);
where culture might be CultureInfo.InvariantCulture, or the current culture etc.
For more on this problem, see the Turkey Test.
If you are using C# then try this code:
Microsoft.VisualBasic.StrConv(sourceString, Microsoft.VisualBasic.vbProperCase)
I use this variant:
private string FirstLetterCapital(string str)
{
return Char.ToUpper(str[0]) + str.Remove(0, 1);
}
If you are sure that str variable is valid (never an empty-string or null), try:
str = Char.ToUpper(str[0]) + str[1..];
Unlike the other solutions that use Substring, this one does not do additional string allocations. This example basically concatenates char with ReadOnlySpan<char>.
I realize this is an old post, but I recently had this problem and solved it with the following method.
private string capSentences(string str)
{
string s = "";
if (str[str.Length - 1] == '.')
str = str.Remove(str.Length - 1, 1);
char[] delim = { '.' };
string[] tokens = str.Split(delim);
for (int i = 0; i < tokens.Length; i++)
{
tokens[i] = tokens[i].Trim();
tokens[i] = char.ToUpper(tokens[i][0]) + tokens[i].Substring(1);
s += tokens[i] + ". ";
}
return s;
}
In the sample below clicking on the button executes this simple code outBox.Text = capSentences(inBox.Text.Trim()); which pulls the text from the upper box and puts it in the lower box after the above method runs on it.
Take the first letter out of the word and then extract it to the other string.
strFirstLetter = strWord.Substring(0, 1).ToUpper();
strFullWord = strFirstLetter + strWord.Substring(1);
text = new String(
new [] { char.ToUpper(text.First()) }
.Concat(text.Skip(1))
.ToArray()
);
this functions makes capital the first letter of all words in a string
public static string FormatSentence(string source)
{
var words = source.Split(' ').Select(t => t.ToCharArray()).ToList();
words.ForEach(t =>
{
for (int i = 0; i < t.Length; i++)
{
t[i] = i.Equals(0) ? char.ToUpper(t[i]) : char.ToLower(t[i]);
}
});
return string.Join(" ", words.Select(t => new string(t)));;
}
string str = "it is a text";
// first use the .Trim() method to get rid of all the unnecessary space at the begining and the end for exemple (" This string ".Trim() is gonna output "This string").
str = str.Trim();
char theFirstLetter = str[0]; // this line is to take the first letter of the string at index 0.
theFirstLetter.ToUpper(); // .ToTupper() methode to uppercase the firstletter.
str = theFirstLetter + str.substring(1); // we add the first letter that we uppercased and add the rest of the string by using the str.substring(1) (str.substring(1) to skip the first letter at index 0 and only print the letters from the index 1 to the last index.)
Console.WriteLine(str); // now it should output "It is a text"
static String UppercaseWords(String BadName)
{
String FullName = "";
if (BadName != null)
{
String[] FullBadName = BadName.Split(' ');
foreach (string Name in FullBadName)
{
String SmallName = "";
if (Name.Length > 1)
{
SmallName = char.ToUpper(Name[0]) + Name.Substring(1).ToLower();
}
else
{
SmallName = Name.ToUpper();
}
FullName = FullName + " " + SmallName;
}
}
FullName = FullName.Trim();
FullName = FullName.TrimEnd();
FullName = FullName.TrimStart();
return FullName;
}
string Input = " it is my text";
Input = Input.TrimStart();
//Create a char array
char[] Letters = Input.ToCharArray();
//Make first letter a capital one
string First = char.ToUpper(Letters[0]).ToString();
//Concatenate
string Output = string.Concat(First,Input.Substring(1));
Try this code snippet:
char nm[] = "this is a test";
if(char.IsLower(nm[0])) nm[0] = char.ToUpper(nm[0]);
//print result: This is a test