Remove characters before character "." - c#

How effectively remove all character in string that placed before character "."?
Input:
Amerika.USA
Output:
USA

You can use the IndexOf method and the Substring method like so:
string output = input.Substring(input.IndexOf('.') + 1);
The above doesn't have error handling, so if a period doesn't exist in the input string, it will present problems.

You could try this:
string input = "lala.bla";
output = input.Split('.').Last();

string input = "America.USA"
string output = input.Substring(input.IndexOf('.') + 1);

String input = ....;
int index = input.IndexOf('.');
if(index >= 0)
{
return input.Substring(index + 1);
}
This will return the new word.

Extension methods I commonly use to solve this problem:
public static string RemoveAfter(this string value, string character)
{
int index = value.IndexOf(character);
if (index > 0)
{
value = value.Substring(0, index);
}
return value;
}
public static string RemoveBefore(this string value, string character)
{
int index = value.IndexOf(character);
if (index > 0)
{
value = value.Substring(index + 1);
}
return value;
}

public string RemoveCharactersBeforeDot(string s)
{
string splitted=s.Split('.');
return splitted[splitted.Length-1]
}

A couple of methods that, if the char does not exists, return the original string.
This one cuts the string after the first occurrence of the pivot:
public static string truncateStringAfterChar(string input, char pivot){
int index = input.IndexOf(pivot);
if(index >= 0) {
return input.Substring(index + 1);
}
return input;
}
This one instead cuts the string after the last occurrence of the pivot:
public static string truncateStringAfterLastChar(string input, char pivot){
return input.Split(pivot).Last();
}

Related

Method that takes a message and index, creates a substring using the index

Problem: I want to write a method that takes a message/index pair like this:
("Hello, I am *Name1, how are you doing *Name2?", 2)
The index refers to the asterisk delimited name in the message. So if the index is 1, it should refer to *Name1, if it's 2 it should refer to *Name2.
The method should return just the name with the asterisk (*Name2).
I have attempted to play around with substrings, taking the first delimited * and ending when we reach a character that isn't a letter, number, underscore or hyphen, but the logic just isn't setting in.
I know this is similar to a few problems on SO but I can't find anything this specific. Any help is appreciated.
This is what's left of my very vague attempt so far. Based on this thread:
public string GetIndexedNames(string message, int index)
{
int strStart = message.IndexOf("#") + "#".Length;
int strEnd = message.LastIndexOf(" ");
String result = message.Substring(strStart, strEnd - strStart);
}
If you want to do it the old school way, then something like:
public static void Main(string[] args)
{
string message = "Hello, I am *Name1, how are you doing *Name2?";
string name1 = GetIndexedNames(message, "*", 1);
string name2 = GetIndexedNames(message, "*", 2);
Console.WriteLine(message);
Console.WriteLine(name1);
Console.WriteLine(name2);
Console.ReadLine();
}
public static string GetIndexedNames(string message, string singleCharDelimiter, int index)
{
string valid = "abcdefghijlmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";
string[] parts = message.Split(singleCharDelimiter.ToArray());
if (parts.Length >= index)
{
StringBuilder sb = new StringBuilder();
for(int i = 0; i < parts[index].Length; i++)
{
string character = parts[index].Substring(i, 1);
if (valid.Contains(character))
{
sb.Append(character);
}
else
{
return sb.ToString();
}
}
return sb.ToString();
}
return "";
}
You can try using regular expressions to match the names. Assuming that name is a sequence of word characters (letters or digits):
using System.Linq;
using System.Text.RegularExpressions;
...
// Either name with asterisk *Name or null
// index is 1-based
private static ObtainName(string source, int index) => Regex
.Matches(source, #"\*\w+")
.Cast<Match>()
.Select(match => match.Value)
.Distinct() // in case the same name repeats several times
.ElementAtOrDefault(index - 1);
Demo:
string name = ObtainName(
"Hello, I am *Name1, how are you doing *Name2?", 2);
Console.Write(name);
Outcome:
*Name2
Perhaps not the most elegant solution, but if you want to use IndexOf, use a loop:
public static string GetIndexedNames(string message, int index, char marker='*')
{
int lastFound = 0;
for (int i = 0; i < index; i++) {
lastFound = message.IndexOf(marker, lastFound+1);
if (lastFound == -1) return null;
}
var space = message.IndexOf(' ', lastFound);
return space == -1 ? message.Substring(lastFound) : message.Substring(lastFound, space - lastFound);
}

C# Get particular string between two string (multiple occurance)

how can I retrieve both string between STRING & END in this sentence
"This is STRING a222 END, and this is STRING b2838 END."
strings that I want to get:
a222
b2838
Following is my code, and i only manage to get first string which is a222
string myString = "This is STRING a222 END, and this is STRING b2838 END.";
int first = myString.IndexOf("STRING") + "STRING".Length;
int second= myString.LastIndexOf("END");
string result = St.Substring(first, second - first);
.
Here is the solution using Regular Expressions. Working Code here
var reg = new Regex("(?<=STRING ).*?(?= END)");
var matched = reg.Matches("This is STRING a222 END, and this is STRING b2838 END.");
foreach(var m in matched)
{
Console.WriteLine(m.ToString());
}
You can pass a value for startIndex to string.IndexOf(), you can use this while looping:
IEnumerable<string> Find(string input, string startDelimiter, string endDelimiter)
{
int first = 0, second;
do
{
// Find start delimiter
first = input.IndexOf(startDelimiter, startIndex: first) + startDelimiter.Length;
if (first == -1)
yield break;
// Find end delimiter
second = input.IndexOf(endDelimiter, startIndex: first);
if (second == -1)
yield break;
yield return input.Substring(first, second - first).Trim();
first = second + endDelimiter.Length + 1;
}
while (first < input.Length);
}
You can iterate over indexes,
string myString = "This is STRING a222 END, and this is STRING b2838 END.";
//Jump to starting index of each `STRING`
for(int i = myString.IndexOf("STRING");i > 0; i = myString.IndexOf("STRING", i+1))
{
//Get Index of each END
var endIndex = myString.Substring(i + "STARTING".Length).IndexOf("END");
//PRINT substring between STRING and END of each occurance
Console.WriteLine(myString.Substring(i + "STARTING".Length-1, endIndex));
}
.NET FIDDLE
In your case, STRING..END occurs multiple times, but you were getting index of only first STRING and last index of END which will return substring, starts with first STRING to last END.
i.e.
a222 END, and this is STRING b2838
You've already got some good answers but I'll add another that uses ReadOnlyMemory from .NET core. That provides a solution that doesn't allocate new strings which can be nice. C# iterators are a common way to transform one sequence, of chars in this case, into another. This method would be used to transform the input string into sequence of ReadOnlyMemory each containing the tokens your after.
public static IEnumerable<ReadOnlyMemory<char>> Tokenize(string source, string beginPattern, string endPattern)
{
if (string.IsNullOrEmpty(source) ||
string.IsNullOrEmpty(beginPattern) ||
string.IsNullOrEmpty(endPattern))
yield break;
var sourceText = source.AsMemory();
int start = 0;
while (start < source.Length)
{
start = source.IndexOf(beginPattern, start);
if (-1 != start)
{
int end = source.IndexOf(endPattern, start);
if (-1 != end)
{
start += beginPattern.Length;
yield return sourceText.Slice(start, (end - start));
}
else
break;
start = end + endPattern.Length;
}
else
{
break;
}
}
}
Then you'd just call it like so to iterate over the tokens...
static void Main(string[] args)
{
const string Source = "This is STRING a222 END, and this is STRING b2838 END.";
foreach (var token in Tokenize(Source, "STRING", "END"))
{
Console.WriteLine(token);
}
}
string myString = "This is STRING a222 END, and this is STRING b2838 END.";
// Fix the issue based on #PaulF's comment.
if (myString.StartsWith("STRING"))
myString = $"DUMP {myString}";
var arr = myString.Split(new string[] { "STRING", "END" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < arr.Length; i++)
{
if(i%2 > 0)
{
// This is your string
Console.WriteLine(arr[i].Trim());
}
}

c#- How can I format an output so that a string always takes up 7 digits?

string name1 = "John";
string name2 = "Alexander";
Console.WriteLine(??);
//desired output:
John Alexand
How can I format the strings so that they will always take up 7 spaces? I'm familiar with how to do this in C, but I cannot find a way to do it for C#.
Use PadRight and SubString
var a = "James";
Console.WriteLine(a.PadRight(7, ' ').Substring(0, 7));
Formatting like $"{name, 7}" ensures that the result will have length at least 7; however, longer inputs will not be trimmed (i.e. "Alexander" will not be trimmed to "Alexand").
We have to impement the logic manually and I suggest hiding it in an extension method:
public static class StringExtensions {
public static string ToLength(this string source, int length) {
if (length < 0)
throw new ArgumentOutOfRangeException("length");
else if (length == 0)
return "";
else if (string.IsNullOrEmpty(source))
return new string(' ', length);
else if (source.Length < length)
return source.PadRight(length);
else
return source.Substring(0, length);
}
}
usage:
Console.WriteLine($"{name1.ToLength(7)} {name2.ToLength(7)}");
I would use an extension method coupled with PadRight()
public void Main() {
string name1 = "John";
string name2 = "Alexander";
string FullName = name1.FixLeft(7) + name2.FixLeft(7);
Console.WriteLine(FullName);
}
private static string FixLeft(this string TextInput, int DesiredLength) {
if (TextInput.Length < DesiredLength) { return TextInput.PadRight(DesiredLength); }
else { return TextInput.Substring(0,DesiredLength); }
}

How to remove all characters from a string before a specific character

Suppose I have a string A, for example:
string A = "Hello_World";
I want to remove all characters up to (and including) the _. The exact number of characters before the _ may vary. In the above example, A == "World" after removal.
string A = "Hello_World";
string str = A.Substring(A.IndexOf('_') + 1);
You have already received a perfectly fine answer. If you are willing to go one step further, you could wrap up the a.SubString(a.IndexOf('_') + 1) in a robust and flexible extension method:
public static string TrimStartUpToAndIncluding(this string str, char ch)
{
if (str == null) throw new ArgumentNullException("str");
int pos = str.IndexOf(ch);
if (pos >= 0)
{
return str.Substring(pos + 1);
}
else // the given character does not occur in the string
{
return str; // there is nothing to trim; alternatively, return `string.Empty`
}
}
which you would use like this:
"Hello_World".TrimStartUpToAndIncluding('_') == "World"
string a = "Hello_World";
a = a.Substring(a.IndexOf("_")+1);
try this? or is the A= part in your A=Hello_World included?
var foo = str.Substring(str.IndexOf('_') + 1);
string orgStr = "Hello_World";
string newStr = orgStr.Substring(orgStr.IndexOf('_') + 1);
you can do this by creating a substring.
simple exampe is here:
public static String removeTillWord(String input, String word) {
return input.substring(input.indexOf(word));
}
removeTillWord("I need this words removed taken please", "taken");

How to insert/remove hyphen to/from a plain string in c#?

I have a string like this;
string text = "6A7FEBFCCC51268FBFF";
And I have one method for which I want to insert the logic for appending the hyphen after 4 characters to 'text' variable. So, the output should be like this;
6A7F-EBFC-CC51-268F-BFF
Appending hyphen to above 'text' variable logic should be inside this method;
public void GetResultsWithHyphen
{
// append hyphen after 4 characters logic goes here
}
And I want also remove the hyphen from a given string such as 6A7F-EBFC-CC51-268F-BFF. So, removing hyphen from a string logic should be inside this method;
public void GetResultsWithOutHyphen
{
// Removing hyphen after 4 characters logic goes here
}
How can I do this in C# (for desktop app)?
What is the best way to do this?
Appreciate everyone's answer in advance.
GetResultsWithOutHyphen is easy (and should return a string instead of void
public string GetResultsWithOutHyphen(string input)
{
// Removing hyphen after 4 characters logic goes here
return input.Replace("-", "");
}
for GetResultsWithHyphen, there may be slicker ways to do it, but here's one way:
public string GetResultsWithHyphen(string input)
{
// append hyphen after 4 characters logic goes here
string output = "";
int start = 0;
while (start < input.Length)
{
output += input.Substring(start, Math.Min(4,input.Length - start)) + "-";
start += 4;
}
// remove the trailing dash
return output.Trim('-');
}
Use regex:
public String GetResultsWithHyphen(String inputString)
{
return Regex.Replace(inputString, #"(\w{4})(\w{4})(\w{4})(\w{4})(\w{3})",
#"$1-$2-$3-$4-$5");
}
and for removal:
public String GetResultsWithOutHyphen(String inputString)
{
return inputString.Replace("-", "");
}
Here's the shortest regex I could come up with. It will work on strings of any length. Note that the \B token will prevent it from matching at the end of a string, so you don't have to trim off an extra hyphen as with some answers above.
using System;
using System.Text.RegularExpressions;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string text = "6A7FEBFCCC51268FBFF";
for (int i = 0; i <= text.Length;i++ )
Console.WriteLine(hyphenate(text.Substring(0, i)));
}
static string hyphenate(string s)
{
var re = new Regex(#"(\w{4}\B)");
return re.Replace (s, "$1-");
}
static string dehyphenate (string s)
{
return s.Replace("-", "");
}
}
}
var hyphenText = new string(
text
.SelectMany((i, ch) => i%4 == 3 && i != text.Length-1 ? new[]{ch, '-'} : new[]{ch})
.ToArray()
)
something along the lines of:
public string GetResultsWithHyphen(string inText)
{
var counter = 0;
var outString = string.Empty;
while (counter < inText.Length)
{
if (counter % 4 == 0)
outString = string.Format("{0}-{1}", outString, inText.Substring(counter, 1));
else
outString += inText.Substring(counter, 1);
counter++;
}
return outString;
}
This is rough code and may not be perfectly, syntactically correct
public static string GetResultsWithHyphen(string str) {
return Regex.Replace(str, "(.{4})", "$1-");
//if you don't want trailing -
//return Regex.Replace(str, "(.{4})(?!$)", "$1-");
}
public static string GetResultsWithOutHyphen(string str) {
//if you just want to remove the hyphens:
//return input.Replace("-", "");
//if you REALLY want to remove hyphens only if they occur after 4 places:
return Regex.Replace(str, "(.{4})-", "$1");
}
For removing:
String textHyphenRemoved=text.Replace('-',''); should remove all of the hyphens
for adding
StringBuilder strBuilder = new StringBuilder();
int startPos = 0;
for (int i = 0; i < text.Length / 4; i++)
{
startPos = i * 4;
strBuilder.Append(text.Substring(startPos,4));
//if it isn't the end of the string add a hyphen
if(text.Length-startPos!=4)
strBuilder.Append("-");
}
//add what is left
strBuilder.Append(text.Substring(startPos, 4));
string textWithHyphens = strBuilder.ToString();
Do note that my adding code is untested.
GetResultsWithOutHyphen method
public string GetResultsWithOutHyphen(string input)
{
return input.Replace("-", "");
}
GetResultsWithOutHyphen method
You could pass a variable instead of four for flexibility.
public string GetResultsWithHyphen(string input)
{
string output = "";
int start = 0;
while (start < input.Length)
{
char bla = input[start];
output += bla;
start += 1;
if (start % 4 == 0)
{
output += "-";
}
}
return output;
}
This worked for me when I had a value for a social security number (123456789) and needed it to display as (123-45-6789) in a listbox.
ListBox1.Items.Add("SS Number : " & vbTab & Format(SSNArray(i), "###-##-####"))
In this case I had an array of Social Security Numbers. This line of code alters the formatting to put a hyphen in.
Callee
public static void Main()
{
var text = new Text("THISisJUSTanEXAMPLEtext");
var convertText = text.Convert();
Console.WriteLine(convertText);
}
Caller
public class Text
{
private string _text;
private int _jumpNo = 4;
public Text(string text)
{
_text = text;
}
public Text(string text, int jumpNo)
{
_text = text;
_jumpNo = jumpNo < 1 ? _jumpNo : jumpNo;
}
public string Convert()
{
if (string.IsNullOrEmpty(_text))
{
return string.Empty;
}
if (_text.Length < _jumpNo)
{
return _text;
}
var convertText = _text.Substring(0, _jumpNo);
int start = _jumpNo;
while (start < _text.Length)
{
convertText += "-" + _text.Substring(start, Math.Min(_jumpNo, _text.Length - start));
start += _jumpNo;
}
return convertText;
}
}

Categories

Resources