I have such a text for example:
"A01+B02+C03+D04+E05+F06+G07+H08+I09+J10+K11+L12+M13+N14+O15+P16"
I would like to add a space after each fourth '+' sign.
This is because if the text is too long in the grid's cell in my page, then it's simply cut off. So I'm thinking to simply wrap the string before binding the data to the grid.
I've played around with several string methods, like getting the IndexOf and the adding a space with Insert, or using a StringBuilder to make a completely new string out of the original one, but I just can't get the final solution running.
Any help would be appreciated.
Thanks.
Use a regex:
Pattern pattern = Pattern.compile("([^+]*\\+){4}");
Matcher matcher = pattern.matcher(str);
matcher.replaceAll("\1 ");
You could use LINQ:
string input = "A01+B02+C03+D04+E05+F06+G07+H08+I09+J10+K11+L12+M13+N14+O15+P16";
string final = string.Join(
"+",
input
.Split('+')
.Select( (s, i) => (i>0 && i%4==0) ? " "+ s : s));
You could just use the CSS word-wrap property to break the string at a certain width...
td.longString {
max-width: 150px;
word-wrap: break-word;
}
Just set CssClass="longString" to the column in question.
Easier:
input = Regex.Replace(input, #"((?:[\w_]+\+){4})", "$1 ");
string text = "A01+B02+C03+D04+E05+F06+G07+H08+I09+J10+K11+L12+M13+N14+O15+P16";
string[] parts = test.Split( '+' );
StringBuilder output = new StringBuilder( );
for( int i = 0; i < parts.Length; i++ )
{
if( i%4 == 0 )
{
output.Append( " " );
}
output.Append( parts[ i ] + "+" );
}
This is the first what comes to my mind. Not the most beautiful though.
var str = "A01+B02+C03+D04+E05+F06+G07+H08+I09+J10+K11+L12+M13+N14+O15+P16";
var strings = str.Split(new [] {'+'});
var builder = new StringBuilder(strings[0]);
for(var i = 1; i< strings.Length;i++)
{
builder.Append(i%4 == 0 ? "+ " : "+");
builder.Append(strings[i]);
}
Regular expressions are all well and good but as someone once said
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.
What about this simple solution isntead:
String testString = "A01+B02+C03+D04+E05+F06+G07+H08+I09+J10+K11+L12+M13+N14+O15+P16";
StringBuilder buffer = new StringBuilder(testString);
int plusCount = 0;
for (int i=0; i<buffer.length(); i++) {
if (buffer.charAt(i) == '+') {
plusCount++;
if (plusCount == 4) {
buffer.insert(i+1, ' ');
i++;
plusCount=0;
}
}
}
Related
I want to do a validation in windows form for allow only one space between the text values. How to do in c#. Thanks in advance.
I don't want to use any other method for this validation only in c#. Please help me to do this.
if (e.Handled = (e.KeyChar == (char)Keys.Space))
{
MessageBox.Show("Spaces are not allowed at start");
}
}
string str = "words with multiple spaces";
Regex regex = new Regex(#"[ ]{2,}", RegexOptions.None);
str = regex.Replace(str, #" "); // "words with multiple spaces"
get your string length and then test each character if it is a white space or not. if it has more than 1 white space, make your function fail.
String myString = "My String";
int myStringLength = myString.length;
int nrOfSpaces = 0;
for(i = 0; i <= myStringLength)
{
if(myString[i] == " ")
{
nrofspaces++;
i++;
}
}
I use Visual Studio 2010 ver.
I have array strings [] = { "eat and go"};
I display it with foreach
I wanna convert strings like this : EAT and GO
Here my code:
Console.Write( myString.First().ToString().ToUpper() + String.Join("",myString].Skip(1)).ToLower()+ "\n");
But the output is : Eat and go . :D lol
Could you help me? I would appreciate it. Thanks
While .ToUpper() will convert a string to its upper case equivalent, calling .First() on a string object actually returns the first element of the string (since it's effectively a char[] under the hood). First() is actually exposed as a LINQ extension method and works on any collection type.
As with many string handling functions, there are a number of ways to handle it, and this is my approach. Obviously you'll need to validate value to ensure it's being given a long enough string.
using System.Text;
public string CapitalizeFirstAndLast(string value)
{
string[] words = value.Split(' '); // break into individual words
StringBuilder result = new StringBuilder();
// Add the first word capitalized
result.Append(words[0].ToUpper());
// Add everything else
for (int i = 1; i < words.Length - 1; i++)
result.Append(words[i]);
// Add the last word capitalized
result.Append(words[words.Length - 1].ToUpper());
return result.ToString();
}
If it's always gonna be a 3 words string, the you can simply do it like this:
string[] mystring = {"eat and go", "fast and slow"};
foreach (var s in mystring)
{
string[] toUpperLower = s.Split(' ');
Console.Write(toUpperLower.First().ToUpper() + " " + toUpperLower[1].ToLower() +" " + toUpperLower.Last().ToUpper());
}
If you want to continuously alternate, you can do the following:
private static string alternateCase( string phrase )
{
String[] words = phrase.split(" ");
StringBuilder builder = new StringBuilder();
//create a flag that keeps track of the case change
book upperToggle = true;
//loops through the words
for(into i = 0; i < words.length; i++)
{
if(upperToggle)
//converts to upper if flag is true
words[i] = words[i].ToUpper();
else
//converts to lower if flag is false
words[i] = words[i].ToLower();
upperToggle = !upperToggle;
//adds the words to the string builder
builder.append(words[i]);
}
//returns the new string
return builder.ToString();
}
Quickie using ScriptCS:
scriptcs (ctrl-c to exit)
> var input = "Eat and go";
> var words = input.Split(' ');
> var result = string.Join(" ", words.Select((s, i) => i % 2 == 0 ? s.ToUpperInvariant() : s.ToLowerInvariant()));
> result
"EAT and GO"
This is the code:
public static string ParseText(string text, int startPos, int endPos)
{
string images = "";
if (startPos >= 0 && endPos > startPos)
{
images = text.Substring(startPos + 1, endPos - startPos - 1);
images.Replace(',',' ');
}
return images;
}
Im using this part to clean/remove , and "
entries = images.Split(new[] { ',' });
for (var i = 0; i < entries.Length; i++)
{
entries[i] = entries[i].Replace("\"", "");
}
For example if i have this part of text:
"http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.cld&datum=201311221800&cultuur=en-GB&continent=europa","http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.cld&datum=201311222100&cultuur=en-GB&continent=europa","http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.cld&datum=201311230000&cultuur=en-GB&continent=europa","http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.cld&datum=201311230300&cultuur=en-GB&continent=europa","http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.cld&datum=201311230600&cultuur=en-GB&continent=europa","http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.cld&datum=201311230900&cultuur=en-GB&continent=europa","
And its longer...But in this example i want to remove all the " and ,
If im using the code as it is now the result is:
Im getting only the first link:
http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.cld&datum=201311221800&cultuur=en-GB&continent=europa
If i remove the lines:
entries = images.Split(new[] { ',' });
for (var i = 0; i < entries.Length; i++)
entries[i] = entries[i].Replace("\"", "");
Then i will see all the text but with , and "
What is wrong with cleaning the , and "?
Why it show me only the first text part and not all the rest ?
strings in C# are immutable.
images.Replace(',', '');
... by design does not affect images. What you need is:
images = images.Replace(',', ' ');
Perhaps you want them as a joined string?
var result = string.Join(Environment.NewLine, images.Split(new[] { ',' }).Select(e => e.Replace("\"", "")));
If I'm understanding your comment correctly,
// could easily be an extension method
public static string ReplacingChars(string source, char[] toReplace, string withThis)
{
return string.Join(withThis, source.Split(toReplace, StringSplitOptions.None));
}
// usage:
images = ReplacingChars(images, new [] {',', '"'}, " ");
Try using string.Replace(). See MSDN for more information.
e.g.
images.Replace(',','');
The following works for me!
string ParseText(string input)
{
// Replace quotes with nothing at all...
var noQuotes = input.Replace("\"", "");
// Replace commas with, I dunno, "whatever you want"...
// If you want to just get rid of the commas, you could use "",
// or if you want a space, " "
return input.Replace("," "whatever you want");
}
I need to remove all additional spaces in a string.
I use regex for matching strings and matched strings i replace with some others.
For better understanding please see examples below:
3 input strings:
Hello, how are you?
Hello , how are you?
Hello , how are you ?
This are 3 strings that should match by one pattern-regex.
It looks something like this:
Hello\s*,\s+how\s+are\s+you\s*?
It works fine but there is a perfomance problem.
If I have a lot of patterns (~20k) and try to execute each pattern it runs very slow (3-5 minutes).
Maybe there is better way for doing this?
for example use some 3d-party libs?
UPD: Folks, this question is not about how to do this. It's about how to do this with best perfomance. :)
Let me explain more detailed. The main goal is tokenize text. (replace some token with special symbols)
For example I have a token "nice try".
Then I input text "this is nice try".
result: "this is #tokenizedtext#" where #tokenizedtext# some special symbols. It doesen't matter in this case.
Next I have string "Mike said it was a nice try".
result should be "Mike said it was a #tokenizedtext#".
I think the main idea is clear.
So I can have a lot of tokens. When I process it I convert my token from "nice try" to pattern "nice\s+try". and try to replace with this pattern input text.
It works fine. But if in tokens there is more spaces and there is also punctuation then my regexes became bigger and works very slow.
Do you have some suggestions (technical or logic) for solving this problem?
I can suggest a few solutions.
First of all, avoid the static Regex method. Create an instance of it (and store it, don't call the constructor for each replacement!) and, if possible, use RegexOptions.Compiled. It should improve your performance.
Second, you can try to review your pattern. I'll do some profiling, but I'm currently undecisive between:
#"(?<=\s)\s+"
With replacement being an empty string or:
#"\s+"
With a space as a replacement. You can try this code, in the meanwhile:
var s = "Hello , how are you?";
var pattern = #"\s+";
var regex = new Regex(pattern, RegexOptions.Compiled);
var replaced = regex.Replace(s, " ");
EDIT: After having done some measurement, the second pattern seems to be faster. I'm editing my sample to adapt it.
EDIT 2: I've written an unsafe method. It's much faster than the other ones presented here, including the Regex ones, but, as the word itself says, it's unsafe. I don't think that there's any problem with the code I've written but I may be wrong -- So please, check it again and again in case there's a bug in the method.
static unsafe string TrimInternal(string input)
{
var length = input.Length;
var array = stackalloc char[length];
fixed (char* fix = input)
{
var ptr = fix;
var counter = 0;
var lastWasSpace = false;
while (*ptr != '\x0')
{
//Current char is a space?
var isSpace = *ptr == ' ';
//If it's a space but the last one wasn't
//Or if it's not a space
if (isSpace && !lastWasSpace || !isSpace)
//Write into the result array
array[counter++] = *ptr;
//The last character (before the next loop) was a space
lastWasSpace = isSpace;
//Increase the pointer
ptr++;
}
return new string(array, 0, counter);
}
}
Usage (compile with /unsafe):
var s = TrimInternal("Hello , how are you?");
Profiling made in Release build, optimizations on, 1000000 iterations:
My above solution with Regex: 00:00:03.2130121
The unsafe solution: 00:00:00.2063467
This might work for you. It should be pretty fast. Note that it also removes spaces at the end of the string; that might not be what you want...
using System;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(">{0}<", RemoveExtraSpaces("Hello, how are you?"));
Console.WriteLine(">{0}<", RemoveExtraSpaces("Hello , how are you?"));
Console.WriteLine(">{0}<", RemoveExtraSpaces("Hello , how are you ?"));
}
public static string RemoveExtraSpaces(string text)
{
var buffer = new char[text.Length];
bool isSpaced = false;
int n = 0;
foreach (char c in text)
{
if (c == ' ')
{
isSpaced = true;
}
else
{
if (isSpaced)
{
if ((c != ',') && (c != '?'))
{
buffer[n++] = ' ';
}
isSpaced = false;
}
buffer[n++] = c;
}
}
return new string(buffer, 0, n);
}
}
}
Something of my own :
find all the position of WhiteSpacechar in string;
private static IEnumerable<int> GetWhiteSpacePos(string input)
{
int iPos = -1;
while ((iPos = input.IndexOf(" ", iPos + 1, StringComparison.Ordinal)) > -1)
{
yield return iPos;
}
}
Remove all whitespace that are in in sequence Returned from GetWhiteSpacePos
string original_string = "Hello , how are you ?";
var poss = GetWhiteSpacePos(original_string).ToList();
int startPos;
int endPos;
StringBuilder builder = new StringBuilder(original_string);
for (int i = poss.Count -1; i > 1; i--)
{
endPos = poss[i];
while ((poss[i] == poss[i - 1] + 1) && i > 1)
{
i--;
}
startPos = poss[i];
if (endPos - startPos > 1)
{
builder.Remove(startPos, endPos - startPos);
}
}
string new_string = builder.ToString();
You are using a very complex regex..simplify the regex and that would definitely increasre the performance
Use \s+ and replace it with a single space
Well, these kind of problems really trouble us. Use this code, and I'm sure you're getting the result for what you've asked. This command removes any extra white space between any string.
cleanString= Regex.Replace(originalString, #"\s", " ");
Hope thar works for you. Thanks.
And since this is a single Instruction. It will utilize less CPU resource and hence less CPU time, which ultimately increases your performance. Therefore A/C to me this method works the best when compared in terms of performance.
if its just a matter of SPACE;
try this
Source : http://www.codeproject.com/Articles/10890/Fastest-C-Case-Insenstive-String-Replace
private static string ReplaceEx(string original,
string pattern, string replacement)
{
int count, position0, position1;
count = position0 = position1 = 0;
string upperString = original.ToUpper();
string upperPattern = pattern.ToUpper();
int inc = (original.Length / pattern.Length) *
(replacement.Length - pattern.Length);
char[] chars = new char[original.Length + Math.Max(0, inc)];
while ((position1 = upperString.IndexOf(upperPattern,
position0)) != -1)
{
for (int i = position0; i < position1; ++i)
chars[count++] = original[i];
for (int i = 0; i < replacement.Length; ++i)
chars[count++] = replacement[i];
position0 = position1 + pattern.Length;
}
if (position0 == 0) return original;
for (int i = position0; i < original.Length; ++i)
chars[count++] = original[i];
return new string(chars, 0, count);
}
Usage:
string original_string = "Hello , how are you ?";
while (original_string.Contains(" "))
{
original_string = ReplaceEx(original_string, " ", " ");
}
Replacing the regex way:
string resultString = null;
try {
resultString = Regex.Replace(subjectString, #"\s+", " ", RegexOption.Compiled);
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
Is there an easy method to insert spaces between the characters of a string? I'm using the below code which takes a string (for example ( UI$.EmployeeHours * UI.DailySalary ) / ( Month ) ) . As this information is getting from an excel sheet, i need to insert [] for each columnname. The issue occurs if user avoids giving spaces after each paranthesis as well as an operator. AnyOne to help?
text = e.Expression.Split(Splitter);
string expressionString = null;
for (int temp = 0; temp < text.Length; temp++)
{
string str = null;
str = text[temp];
if (str.Length != 1 && str != "")
{
expressionString = expressionString + "[" + text[temp].TrimEnd() + "]";
}
else
expressionString = expressionString + str;
}
User might be inputing something like (UI$.SlNo-UI+UI$.Task)-(UI$.Responsible_Person*UI$.StartDate) while my desired output is ( [UI$.SlNo-UI] + [UI$.Task] ) - ([UI$.Responsible_Person] * [UI$.StartDate] )
Here is a short way to insert spaces after every single character in a string (which I know isn't exactly what you were asking for):
var withSpaces = withoutSpaces.Aggregate(string.Empty, (c, i) => c + i + ' ');
This generates a string the same as the first, except with a space after each character (including the last character).
You can do that with regular expressions:
using System.Text.RegularExpressions;
class Program {
static void Main() {
string expression = "(UI$.SlNo-UI+UI$.Task)-(UI$.Responsible_Person*UI$.StartDate) ";
string replaced = Regex.Replace(expression, #"([\w\$\.]+)", " [ $1 ] ");
}
}
If you are not familiar with regular expressions this might look rather cryptic, but they are a powerful tool, and worth learning. In case, you may check how regular expressions work, and use a tool like Expresso to test your regular expressions.
Hope this helps...
Here is an algorithm that does not use regular expressions.
//Applies dobule spacing between characters
public static string DoubleSpace(string s)
{
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
char[] a = s.ToCharArray();
char[] b = new char[ (a.Length * 2) - 1];
int bIndex = 0;
for(int i = 0; i < a.Length; i++)
{
b[bIndex++] = a[i];
//Insert a white space after the char
if(i < (a.Length - 1))
{
b[bIndex++] = ' ';
}
}
return new string(b);
}
Well, you can do this by using Regular expressions, search for specific paterns and add brackets where needed. You could also simply Replace every Paranthesis with the same Paranthesis but with spaces on each end.
I would also advice you to use StringBuilder aswell instead of appending to an existing string (this creates a new string for each manipulation, StringBuilder has a smaller memory footprint when doing this kind of manipulation)