I am retrieving data from a DB table using SqlDataReader in ASP.net. I append the retrieved data in a string builder and after that, dump the contents of the string builder into a text file. My problem is that in that text file white spaces are showing up between one column and another ... How can I remove the excess white spaces from my text file?
Thanks in advance.
1. Text.Trim();
2. Text.Replace(" ", string.empty);
private string process(string s)
{
int len = s.Length;
int current=0;
StringBuilder sb = new StringBuilder(len);
while (current < len-1)
{
if (!(s[current] == ' ' && s[current + 1] == ' ') &&
!(s[current] == '\n' && s[current + 1] == '\n')
)
{
sb.Append(s[current]);
}
current++;
}
return sb.ToString();
}
Related
I have a reader which is defined as follows:
CSVReader csvReader =new CSVReader(new InputStreamReader(inputStream), ',', '\'');
StringBuilder stringBuilder = new StringBuilder();
String[] line;
if (SPECIAL_CHARS == null || SPECIAL_CHARS.length == 0) {
return inputStream;
}
String[] stringArrSpecialChars = new String(SPECIAL_CHARS).split("");
while ((line = csvReader.readNext()) != null) {
//do somthing
}
how ever it throws this error:
java.io.IOException: Unterminated quoted field at end of CSV line. Beginning of lost text: [D'Olra
when it encounter a CSV cell with: D'Olra
Any advise ?
Fixed by replacing the first line with:
char charThatWillNotAppearInText = 127;
CSVReader csvReader = new CSVReader(new InputStreamReader(inputStream), ',', charThatWillNotAppearInText);
This is a workaround that disable the 'quotechar' option under the assumption that char with 127 will never be part of the input CSV file.
Use OpenCSV as:
com.opencsv.CSVParser parser = new CSVParserBuilder().withIgnoreQuotations(true).withSeparator('|').build()
Using .Net 2.0 how can i check if a multi line text box has only newline characters?
No text at all, but only \n, \r, etc..?
if (Regex.IsMatch(#"^[\r\n]+$", text))
You can use String.IsNullOrWhiteSpace method.
if(!string.IsNullOrWhiteSpace(TextBox1.Text))
{
}
Here is the source of IsNullOrWhiteSpace -
public static bool IsNullOrWhiteSpace(string value)
{
if (value == null)
return true;
for (int index = 0; index < value.Length; ++index)
{
if (!char.IsWhiteSpace(value[index]))
return false;
}
return true;
}
Have you tried replacing Environment.NewLine with nothing?
For example,
Dim tbLen as Integer = tb.Text.Length() 'returns 2 for 1 return character
Dim tbLenFiltered As Integer = tb.Text.Replace(Environment.NewLine, String.Empty).Length() 'returns 0 for 1 return character
I am trying to insert the word "and" before the last word in a string. This is my code so far:
string skillset = "";
foreach (ListItem item in SkillSet.Items)
{
if (item.Selected)
{
skillset += item.Text + ", ";
}
}
skillset = skillset.Substring(0, skillset.Length - 2);
Any help is greatly appreciated.
Thanks
Thomas
If you just want to put "and" in fron of the last word you can use to split your string into an array of strings, change the last word and join the string back together. It would look something like this
string[] skills = skillset.Split(new char[] { ',' });
skills[skills.Length-1] = "and " + skills[skills.Length-1];
skillset = string.Join(",", skills);
This returns a new string in which a specified string is inserted at a specified index position.
Example
string str = "We are loudly";
string mynewvalue = "talking";
str.Insert(str.Length - 1, mynewvalue);
int myStringLength = myString.length;
string myString = inputString.Substring(0, myStringLength);
int index = myString.LastIndexOf(' ');
string outputString = myString.Insert(index , " and ");
Example : http://www.dotnetperls.com/insert
I need to remove spaces from the end of a string. How can I do that?
Example: if string is "Hello " it must become "Hello"
Taken from this answer here: https://stackoverflow.com/a/5691567/251012
- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet {
NSRange rangeOfLastWantedCharacter = [self rangeOfCharacterFromSet:[characterSet invertedSet]
options:NSBackwardsSearch];
if (rangeOfLastWantedCharacter.location == NSNotFound) {
return #"";
}
return [self substringToIndex:rangeOfLastWantedCharacter.location+1]; // non-inclusive
}
Another solution involves creating mutable string:
//make mutable string
NSMutableString *stringToTrim = [#" i needz trim " mutableCopy];
//pass it by reference to CFStringTrimSpace
CFStringTrimWhiteSpace((__bridge CFMutableStringRef) stringToTrim);
//stringToTrim is now "i needz trim"
Here you go...
- (NSString *)removeEndSpaceFrom:(NSString *)strtoremove{
NSUInteger location = 0;
unichar charBuffer[[strtoremove length]];
[strtoremove getCharacters:charBuffer];
int i = 0;
for(i = [strtoremove length]; i >0; i--) {
NSCharacterSet* charSet = [NSCharacterSet whitespaceCharacterSet];
if(![charSet characterIsMember:charBuffer[i - 1]]) {
break;
}
}
return [strtoremove substringWithRange:NSMakeRange(location, i - location)];
}
So now just call it. Supposing you have a string that has spaces on the front and spaces on the end and you just want to remove the spaces on the end, you can call it like this:
NSString *oneTwoThree = #" TestString ";
NSString *resultString;
resultString = [self removeEndSpaceFrom:oneTwoThree];
resultString will then have no spaces at the end.
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//for remove whitespace and new line character
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet punctuationCharacterSet]];
//for remove characters in punctuation category
There are many other CharacterSets. Check it yourself as per your requirement.
To remove whitespace from only the beginning and end of a string in Swift:
Swift 3
string.trimmingCharacters(in: .whitespacesAndNewlines)
Previous Swift Versions
string.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()))
Swift version
Only trims spaces at the end of the String:
private func removingSpacesAtTheEndOfAString(var str: String) -> String {
var i: Int = countElements(str) - 1, j: Int = i
while(i >= 0 && str[advance(str.startIndex, i)] == " ") {
--i
}
return str.substringWithRange(Range<String.Index>(start: str.startIndex, end: advance(str.endIndex, -(j - i))))
}
Trims spaces on both sides of the String:
var str: String = " Yolo "
var trimmedStr: String = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
This will remove only the trailing characters of your choice.
func trimRight(theString: String, charSet: NSCharacterSet) -> String {
var newString = theString
while String(newString.characters.last).rangeOfCharacterFromSet(charSet) != nil {
newString = String(newString.characters.dropLast())
}
return newString
}
In Swift
To trim space & newline from both side of the String:
var url: String = "\n http://example.com/xyz.mp4 "
var trimmedUrl: String = url.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
A simple solution to only trim one end instead of both ends in Objective-C:
#implementation NSString (category)
/// trims the characters at the end
- (NSString *)stringByTrimmingSuffixCharactersInSet:(NSCharacterSet *)characterSet {
NSUInteger i = self.length;
while (i > 0 && [characterSet characterIsMember:[self characterAtIndex:i - 1]]) {
i--;
}
return [self substringToIndex:i];
}
#end
And a symmetrical utility for trimming the beginning only:
#implementation NSString (category)
/// trims the characters at the beginning
- (NSString *)stringByTrimmingPrefixCharactersInSet:(NSCharacterSet *)characterSet {
NSUInteger i = 0;
while (i < self.length && [characterSet characterIsMember:[self characterAtIndex:i]]) {
i++;
}
return [self substringFromIndex:i];
}
#end
To trim all trailing whitespace characters (I'm guessing that is actually your intent), the following is a pretty clean & concise way to do it.
Swift 5:
let trimmedString = string.replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression)
Objective-C:
NSString *trimmedString = [string stringByReplacingOccurrencesOfString:#"\\s+$" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, string.length)];
One line, with a dash of regex.
The solution is described here: How to remove whitespace from right end of NSString?
Add the following categories to NSString:
- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet {
NSRange rangeOfLastWantedCharacter = [self rangeOfCharacterFromSet:[characterSet invertedSet]
options:NSBackwardsSearch];
if (rangeOfLastWantedCharacter.location == NSNotFound) {
return #"";
}
return [self substringToIndex:rangeOfLastWantedCharacter.location+1]; // non-inclusive
}
- (NSString *)stringByTrimmingTrailingWhitespaceAndNewlineCharacters {
return [self stringByTrimmingTrailingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
And you use it as such:
[yourNSString stringByTrimmingTrailingWhitespaceAndNewlineCharacters]
I came up with this function, which basically behaves similarly to one in the answer by Alex:
-(NSString*)trimLastSpace:(NSString*)str{
int i = str.length - 1;
for (; i >= 0 && [str characterAtIndex:i] == ' '; i--);
return [str substringToIndex:i + 1];
}
whitespaceCharacterSet besides space itself includes also tab character, which in my case could not appear. So i guess a plain comparison could suffice.
let string = " Test Trimmed String "
For Removing white Space and New line use below code :-
let str_trimmed = yourString.trimmingCharacters(in: .whitespacesAndNewlines)
For Removing only Spaces from string use below code :-
let str_trimmed = yourString.trimmingCharacters(in: .whitespaces)
NSString* NSStringWithoutSpace(NSString* string)
{
return [string stringByReplacingOccurrencesOfString:#" " withString:#""];
}
how can i convert a string to a Decimal(10,2) in C#?
Take a look at Decimal.TryParse, especially if the string is coming from a user.
You'll want to use TryParse if there's any chance the string cannot be converted to a Decimal. TryParse allows you to test if the conversion will work without throwing an Exception.
You got to be careful with that, because some cultures uses dots as a thousands separator and comma as a decimal separator.
My proposition for a secure string to decimal converstion:
public static decimal parseDecimal(string value)
{
value = value.Replace(" ", "");
if (System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator == ",")
{
value = value.Replace(".", ",");
}
else
{
value = value.Replace(",", ".");
}
string[] splited = value.Split(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0]);
if (splited.Length > 2)
{
string r = "";
for (int i = 0; i < splited.Length; i++)
{
if (i == splited.Length - 1)
r += System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
r += splited[i];
}
value = r;
}
return decimal.Parse(value);
}
The loop is in case that string contains both, decimal and thousand separator
Try:
string test = "123";
decimal test2 = Convert.ToDecimal(test);
//decimal test2 = Decimal.Parse(test);
//decimal test2;
// if (decimal.TryParse(test, out result))
//{ //valid }
//else
//{ //Exception }
labelConverted.Text = test2.toString();
Decimal Examples
Difference between Convert.ToDecimal(string) & Decimal.Parse(string)
Regards