---
# System prepended metadata

title: 2296. Design a Text Editor
tags: [Leetcode, Hard, Stack]

---

# 2296. Design a Text Editor
###### tags: `Leetcode` `Hard` `Stack`
Link: https://leetcode.com/problems/design-a-text-editor/
## 思路
题目不难 就是很麻烦 要考虑清楚edge case
用stringbuilder做
## Code
```java=
class TextEditor {
    StringBuilder sb;
    int idx;
    
    public TextEditor() {
        sb = new StringBuilder(); 
        idx = 0;
    }
    
    public void addText(String text) {
        sb.insert(idx,text);
        idx = idx+text.length();
    }
    
    public int deleteText(int k) {
        sb.delete(Math.max(0, idx-k), idx);
        int len = Math.min(idx, k);
        idx = Math.max(0, idx-k);
        return len;
    }
    
    public String cursorLeft(int k) {
        idx = Math.max(idx-k, 0);
        StringBuilder temp = new StringBuilder();
        int tempIdx = idx-1;
        while(tempIdx>=0 && temp.length()<10){
            temp.insert(0, sb.charAt(tempIdx));
            tempIdx--;
        }
        return temp.toString();
    }
    
    public String cursorRight(int k) {
        idx = Math.min(k+idx, sb.length());
        StringBuilder temp = new StringBuilder();
        int tempIdx = idx-1;
        while(tempIdx>=0 && temp.length()<10){
            temp.insert(0,sb.charAt(tempIdx));
            tempIdx--;
        }
        return temp.toString();
    }
}

```