Format "12345678" to "1234-5678" - c#

How to format a string of numbers "12345678" to "1234-5678".
string str = "12345678";
//I want to format it like below
res = "1234-5678";
Thanks

You can use string.Insert:
string res = "12345678".Insert(4, "-");
The parameters are the index to insert into and the string to insert.

In case you need to format numbers, you can use String.Format() method:
int test = 12345678;
string res = String.Format("{0:####-####}", test); // res == "1234-5678"

How I could understand your desirable format is: to insert a hyphen after first four symbols in the string. if so, then It is very simple:
res = str.Length > 4 ? string.Concat (str.Substring (0, 4), "-", str.Substring (4)) : str;
If your format is other, please descride it in details.

You can also use .Substring like so:
string str1 = str.Substring(0,4);
string str2 = str.Substring(4,4);
string res = str1 + "-" + str2;

I used Visual Basic Code
It is not hard to convert on C#
Dim str As String = "12345678"
Dim num As Long = CLng(str)
Dim strOut As String = Format(num, "####-####")

Related

String replace in specific positioned in c#

I have a string Classic-T50 (Black+Grey)
when i send to by query string it will show in next page
Classic-T50 (Black Grey)
so i want to add + in space in this string only within bracket() only portion.
Classic-T50 (Black+Grey).
I have tried string.Replace(" ","+").But it produce
Classic-T50+(Black+Grey).
But i want string Classic-T50 (Black+Grey).
Help me please.
You can use a regular expression for replacing all spaces inside brackets:
var pattern = #"\s(?![^)]*\()";
var data = "Classic-T50 (Black Grey)";
var replacement = "+";
var regex = new Regex(pattern);
var transformedData = regex.Replace(data, replacement); // Classic-T50 (Black+Grey)
This approach will work for any input string. E.g., the string Caption ( A B C D ) will transform to Caption (+A+B+C+D+).
Additional links:
Regex explanation: https://regex101.com/r/aN8fV2/1
MSDN: Regex.Replace Method (String, String)
What is the format of the strings that you want to modify? Will this code work?
void Main()
{
var str = "Classic-T50 (Black Grey)";
Console.WriteLine(FormatWithPlus(str));
}
public string FormatWithPlus(string str){
var str1 = str.Substring(0, str.IndexOf('('));
var str2 = str.Substring(str.IndexOf('('));
return str1 + str2.Replace(' ', '+');
}
Use a StringBuilder and convert back to string. StringBuilder's differ from strings in that they're mutable and noninterned. It stores data in an array, and so you can replace characters like you would in an array:
void Main()
{
var input = "Classic-T50 (Black Grey)";
StringBuilder inputsb = new StringBuilder(input);
var openParens = input.IndexOf('(');
var closeParens = input.IndexOf(')');
var count = closeParens - openParens;
//Console.WriteLine(input);
//inputsb[18] = '+';
inputsb.Replace(' ', '+', openParens, count);
Console.WriteLine(inputsb.ToString());
}
See StringBuilder.Replace Method (Char, Char, Int32, Int32
try:
String.Replace("k ","k+")
use this code
public class Program
{
private static void Main(string[] args)
{
const string abc = "Classic-T50 (Black Grey)";
var a = abc.Replace("k ", "k+");
Console.WriteLine(a);
Console.ReadKey();
}
}
You can UrlEncode it to preserve the special character:
Server.UrlEncode(mystring)
Or replace + sign with "%252b" and then encode it:
string myTitle = mystring.Trim().Replace("+", "%252b");
Response.Redirect("~/default.aspx?title=" + Server.UrlEncode(myTitle));
Remember to decode it once you try to retrieve it :
Server.UrlDecode(Request.QueryString["title"]);

Remove characters from a specific index character

I would like to know how can i remove characters in a string from a specific index like :
string str = "this/is/an/example"
I want to remove all characters from the third '/' including so it would be like this:
str = "this/is/an"
I tried with substring and regex but i cant find a solution.
Using string operations:
str = str.Substring(0, str.IndexOf('/', str.IndexOf('/', str.IndexOf('/') + 1) + 1));
Using regex:
str = Regex.Replace(str, #"^(([^/]*/){2}[^/]*)/.*$", "$1");
To get "this/is/an":
string str = "this/is/an/example";
string new_string = str.Remove(str.LastIndexOf('/'));
If you need to keep the slash:
string str = "this/is/an/example";
string new_string = str.Remove(str.LastIndexOf('/')+1);
This expects there to be at least one slash. If none are present, you should check it beforehand to not throw an exception:
string str = "this.s.an.example";
string newStr = str;
if (str.Contains('/'))
newStr = str.Remove(str.LastIndexOf('/'));
If its importaint to get the third one, make a dynamic method for it, like this. Input the string, and which "folder" you want returned. 3 in your example will return "this/is/an":
static string ReturnNdir(string sDir, int n)
{
while (sDir.Count(s => s == '/') > n - 1)
sDir = sDir.Remove(sDir.LastIndexOf('/'));
return sDir;
}
This regex is the answer: ^[^/]*\/[^/]*\/[^/]*. It will capture the first three chunks.
var regex = new Regex("^[^/]*\\/[^/]*\\/[^/]*", RegexOptions.Compiled);
var value = regex.Match(str).Value;
I think the best way of doing that it's creating a extension
string str = "this/is/an/example";
str = str.RemoveLastWord();
//specifying a character
string str2 = "this.is.an.example";
str2 = str2.RemoveLastWord(".");
With this static class:
public static class StringExtension
{
public static string RemoveLastWord(this string value, string separator = "")
{
if (string.IsNullOrWhiteSpace(value))
return string.Empty;
if (string.IsNullOrWhiteSpace(separator))
separator = "/";
var words = value.Split(Char.Parse(separator));
if (words.Length == 1)
return value;
value = string.Join(separator, words.Take(words.Length - 1));
return value;
}
}

Extract some numbers and decimals from a string

I have a string:
" a.1.2.3 #4567 "
and I want to reduce that to just "1.2.3".
Currently using Substring() and Remove(), but that breaks if there ends up being more numbers after the pound sign.
What's the best way to go about doing this? I've read a bunch of questions on regex & string.split, but I can't get anything I try to work in VB.net. Would I have to do a match then replace using the match result?
Any help would be much appreciated.
This should work:
string input = " a.1.2.3 #4567 ";
int poundIndex = input.IndexOf("#");
if(poundIndex >= 0)
{
string relevantPart = input.Substring(0, poundIndex).Trim();
IEnumerable<Char> numPart = relevantPart.SkipWhile(c => !Char.IsDigit(c));
string result = new string(numPart.ToArray());
}
Demo
Try this...
String[] splited = split("#");
String output = splited[0].subString(2); // 1 is the index of the "." after "a" considering there are no blank spaces before it..
Here is regex way of doing it
string input = " a.1.2.3 #4567 ";
Regex regex = new Regex(#"(\d\.)+\d");
var match = regex.Match(input);
if(match.Success)
{
string output = match.Groups[0].Value;//"1.2.3"
//Or
string output = match.Value;//"1.2.3"
}
If the pound sign is the most relevant bit, rely on Split. Sample VB.NET code:
Dim inputString As String = " a.1.2.3 #4567 "
If (inputString.Contains("#")) Then
Dim firstBit As String = inputString.Split("#")(0).Trim()
Dim headingToRemove As String = "a."
Dim result As String = firstBit.Substring(headingToRemove.Length, firstBit.Length - headingToRemove.Length)
End If
As far as this is a multi-language question, here comes the translation to C#:
string inputString = " a.1.2.3 #4567 ";
if (inputString.Contains("#"))
{
string firstBit = inputString.Split('#')[0].Trim();
string headingToRemove = "a.";
string result = firstBit.Substring(headingToRemove.Length, firstBit.Length - headingToRemove.Length);
}
I guess another way using unrolled
\d+ (?: \. \d+ )+

Retrieving string from a string which is in between two String?

i have a string Like
"Hello i want to go."
my code give "want to go."
but i need string between " i " and " to " how can i get this? my code is as below.
string[] words = Regex.Split("Hello i want to go.", " i ");
string respons = words[1];
string input = "Hello i want to go.";
Regex regex = new Regex(#".*\s[Ii]{1}\s(\w*)\sto\s.*");
Match match = regex.Match(input);
string result = string.Empty;
if (match.Success)
{
result = match.Groups[1].Value;
}
This regex will match any 'word' between 'i' (not case sensitive) and 'to'.
EDIT: changed ...to.* => to\s.* as suggested in the comments.
string input = "Hello I want to go.";
string result = input.Split(" ")[2];
If you want the word after the "i" then:
string result = input.Split(" i ")[1].Split(" ")[0];
Use
string s = "Hello i want to go.";
string[] words = s.split(' ');
string response = wor
just do it with one simple line of code
var word = "Hello i want to go.".Split(' ')[2];
//Returns the word "want"
string input = "Hello I want to go.";
string[] sentenceArray = input.Split(' ');
string required = sentenceArray[2];
Here's an example using Regex which gives you the index of each occurrence of "want":
string str = "Hello i want to go. Hello i want to go. Hello i want to go.";
Match match = Regex.Match(str, "want");
while(match.Success){
Console.WriteLine(string.Format("Index: {0}", match.Index));
match = match.NextMatch();
}
Nowhere does it say Regex...
string result = input.Split.Skip(2).Take(1).First()
it's work
public static string Between(this string src, string findfrom, string findto)
{
int start = src.IndexOf(findfrom);
int to = src.IndexOf(findto, start + findfrom.Length);
if (start < 0 || to < 0) return "";
string s = src.Substring(
start + findfrom.Length,
to - start - findfrom.Length);
return s;
}
and it can be called as
string respons = Between("Hello i want to go."," i "," to ");
it return want

How to split string using Substring

I have a string like '/Test1/Test2', and i need to take Test2 separated from the same. How can i do that in c# ?
Try this:
string toSplit= "/Test1/Test2";
toSplit.Split('/');
or
toSplit.Split(new [] {'/'}, System.StringSplitOptions.RemoveEmptyEntries);
to split, the latter will remove the empty string.
Adding .Last() will get you the last item.
e.g.
toSplit.Split('/').Last();
Use .Split().
string foo = "/Test1/Test2";
string extractedString = foo.Split('/').Last(); // Result Test2
This site have quite a few examples of splitting strings in C#. It's worth a read.
Using .Split and a little bit of LINQ, you could do the following
string str = "/Test1/Test2";
string desiredValue = str.Split('/').Last();
Otherwise you could do
string str = "/Test1/Test2";
string desiredValue = str;
if(str.Contains("/"))
desiredValue = str.Substring(str.LastIndexOf("/") + 1);
Thanks Binary Worrier, forgot that you'd want to drop the '/', darn fenceposts
string[] arr = string1.split('/');
string result = arr[arr.length - 1];
string [] split = words.Split('/');
This will give you an array split that will contain "", "Test1" and "Test2".
If you just want the Test2 portion, try this:
string fullTest = "/Test1/Test2";
string test2 = test.Split('/').ElementAt(1); //This will grab the second element.
string inputString = "/Test1/Test2";
string[] stringSeparators = new string[] { "/Test1/"};
string[] result;
result = inputString.Split(stringSeparators,
StringSplitOptions.RemoveEmptyEntries);
foreach (string s in result)
{
Console.Write("{0}",s);
}
OUTPUT : Test2

Categories

Resources