Question #58MediumFlutter Basics

Flutter how to change the first letter capital in all of this “Hello print my Name”; change this to “HelloprintmyName”;

#flutter#api

Answer

Solution

To remove all spaces from a string (convert "Hello print my Name" to "HelloprintmyName").


Method 1: Using replaceAll()

dart
String removeSpaces(String text) {
  return text.replaceAll(' ', '');
}

void main() {
  String input = "Hello print my Name";
  String output = removeSpaces(input);
  print(output); // HelloprintmyName
}

Method 2: Using split() and join()

dart
String removeSpaces(String text) {
  return text.split(' ').join('');
}

void main() {
  String input = "Hello print my Name";
  String output = removeSpaces(input);
  print(output); // HelloprintmyName
}

Method 3: Using RegExp (Remove All Whitespace)

dart
String removeAllWhitespace(String text) {
  // Removes all whitespace (spaces, tabs, newlines)
  return text.replaceAll(RegExp(r'\s+'), '');
}

void main() {
  String input = "Hello print my Name";
  String output = removeAllWhitespace(input);
  print(output); // HelloprintmyName

  // Also handles tabs and newlines
  String input2 = "Hello\tprint\nmy Name";
  print(removeAllWhitespace(input2)); // HelloprintmyName
}

Method 4: Extension Method

dart
extension StringExtension on String {
  String removeSpaces() {
    return replaceAll(' ', '');
  }

  String removeAllWhitespace() {
    return replaceAll(RegExp(r'\s+'), '');
  }
}

void main() {
  String input = "Hello print my Name";
  print(input.removeSpaces()); // HelloprintmyName

  String input2 = "Hello   print  \n  my Name";
  print(input2.removeAllWhitespace()); // HelloprintmyName
}

Method 5: Capitalize First Letter of Each Word (No Spaces)

If you also want to capitalize the first letter of each word:

dart
String capitalizeAndRemoveSpaces(String text) {
  return text.split(' ').map((word) {
    if (word.isEmpty) return word;
    return word[0].toUpperCase() + word.substring(1).toLowerCase();
  }).join('');
}

void main() {
  String input = "Hello print my Name";
  String output = capitalizeAndRemoveSpaces(input);
  print(output); // HelloPrintMyName
}

Complete Widget Example

dart
class RemoveSpacesWidget extends StatefulWidget {
  
  _RemoveSpacesWidgetState createState() => _RemoveSpacesWidgetState();
}

class _RemoveSpacesWidgetState extends State<RemoveSpacesWidget> {
  final TextEditingController _controller = TextEditingController();
  String _output = '';

  void _removeSpaces() {
    setState(() {
      _output = _controller.text.replaceAll(' ', '');
    });
  }

  void _capitalizeAndRemoveSpaces() {
    setState(() {
      _output = _controller.text.split(' ').map((word) {
        if (word.isEmpty) return word;
        return word[0].toUpperCase() + word.substring(1).toLowerCase();
      }).join('');
    });
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Remove Spaces')),
      body: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          children: [
            TextField(
              controller: _controller,
              decoration: InputDecoration(
                labelText: 'Enter text',
                hintText: 'Hello print my Name',
              ),
            ),
            SizedBox(height: 16),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                  onPressed: _removeSpaces,
                  child: Text('Remove Spaces'),
                ),
                ElevatedButton(
                  onPressed: _capitalizeAndRemoveSpaces,
                  child: Text('Capitalize + Remove'),
                ),
              ],
            ),
            SizedBox(height: 16),
            Text(
              'Output: $_output',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
          ],
        ),
      ),
    );
  }
}

Comparison of Methods

MethodCodeUse Case
replaceAll(' ', '')SimpleRemove only spaces
split(' ').join('')FunctionalRemove only spaces
replaceAll(RegExp(r'\s+'), '')PowerfulRemove all whitespace (spaces, tabs, newlines)
Extension methodReusableClean syntax, reusable

Expected Output

Simple Remove Spaces

dart
Input:  "Hello print my Name"
Output: "HelloprintmyName"

Input:  "i   love   dart"
Output: "ilovedart"

Remove All Whitespace (including tabs/newlines)

dart
Input:  "Hello\tprint\nmy Name"
Output: "HelloprintmyName"

Input:  "Hello   print  \n  my Name"
Output: "HelloprintmyName"

Capitalize + Remove Spaces

dart
Input:  "Hello print my Name"
Output: "HelloPrintMyName"

Input:  "i love dart programming"
Output: "ILoveDartProgramming"

Difference Between Questions 57 and 58

QuestionGoalExample
Q57Capitalize each word, keep spaces"Hello print my Name" → "Hello Print My Name"
Q58Remove all spaces"Hello print my Name" → "HelloprintmyName"

Key String Methods

dart
String text = "Hello World";

// Remove specific character
text.replaceAll('o', '');  // "Hell Wrld"

// Remove all whitespace
text.replaceAll(RegExp(r'\s+'), '');  // "HelloWorld"

// Split by spaces
text.split(' ');  // ['Hello', 'World']

// Join array
['Hello', 'World'].join('');  // "HelloWorld"

// Trim (remove leading/trailing whitespace)
"  Hello  ".trim();  // "Hello"

Resources